Thinking on hiring me?

Please read

Fernando Guillén

a Freelance Web Developer

cabecera decorativa

software development as an artistic expression

Ruby, script generador de script javascript para precarga de imágenes en tu html

El truco más sencillo para precargar las imágenes de tu web y así no ver el horrible efecto de mouse-over hueco es hacer un script javascript como este:

img1 = new Image();
img1.src="imagen.jpg";

Esto invocará la imagen y el navegador, sino es muy tonto, la dejará en la caché para cuando verdaderamente la necesite.

Bueno, pues es lo que quiero hacer para una web que tiene un montón de background-image definidos en su css.

Para ello me he hecho un script en ruby que me busca todas las imágenes en todos los css y me genera un script de javascript con todo el rollito de los preload.

class Preloator
  def self.generate_script( css_directory )
    # take all .css on directory
    css_file_names = []
    Dir.foreach( css_directory ) do |file|
      if file =~ /.*\.css$/
        css_file_names << css_directory + '/' + file
      end
    end
 
    # take all the images by looking at 'url'
    image_names = []
    css_file_names.each do |file_name|
      self.grep( 'url', file_name ).each do |line|
        image_names << line.scan( /.*\((.*)\)/ ).flatten.first
      end
    end
 
    # generate the script
    script = "<script>\n"
    image_names.each_with_index do |image_name, index|
      script += "    img#{index} = new Image();\n"
      script += "    img#{index}.src = \"#{image_name}\";\n"
    end
    script += "</script>"
  end
 
  def self.grep( pattern, filename )
    matches = []
    regexp = Regexp.new( pattern )
    File.open(filename) do |file|
      file.each do |line|
        matches << "#{filename} #{file.lineno.to_s}: #{line}" if regexp.match(line)
      end
    end
    matches
  end
end
 
puts Preloator.generate_script( ARGV[0] )

Esto genera una salida como esta:

$ ruby etc/preloator.rb public/stylesheets/
<script>
img0 = new Image();
img0.src="/imgs/fondo.jpg";
img1 = new Image();
img1.src="/imgs/fondo_carpeta.png";
img2 = new Image();
img2.src="/imgs/blog_sombra_abajo.png";
img3 = new Image();
</script>;

Seguramente quieras mejorarlo un poquito: meterlo en un .js o invocarlo cuando el document.load.

El script ahorra trabajo si, como en mi caso, tienes más de 20 imágenes en el css.. y escribir el javascript a mano sería un coñazo.

7 Comments to “Ruby, script generador de script javascript para precarga de imágenes en tu html”
  1. Damu Says:

    Lo de precargar imagenes lo he hecho alguna vez con una solucion de menor tecnologia, sin js, solo usando un div oculto con las imagenes dentro. ;-)

  2. fguillen Says:

    Sip.. también vale :), lo único que el javascript lo puedes ejecutar cuando toda la página ha sido cargada y así le permites al usuario verla e interactuar.. Si cargas las imágenes dentro del HTML puede que el navegador se quede tonto hasta que acabe.

  3. Victorina Says:

    You may also decide the exact quantity of private data that’s going to be revealed when making use of the webcams and you could even decide to have secrets when it
    comes to your personal information. The term
    polyamory actually means that both parties in the relationship approve of having
    sex with people outside the relationship so this is a contradiction in terms.
    In what ways could you overcome any negative impacts past experiences have caused.
    Right here we won’t be talking about what are the perfect sexual positions,
    or how to remember to him or her with your fantastic oral
    intercourse techniques.

  4. Jestine Says:

    Hey would you mind letting me know which hosting company you’re using?
    I’ve loaded your blog in 3 completely different web browsers and I must say this blog loads a lot faster then most.
    Can you suggest a good hosting provider at a honest price?
    Thank you, I appreciate it!

    Also visit my web blog :: 安心 トートバッグ 最安値 (Jestine)

  5. www.imphobbies.com Says:

    Best of all, online dating provides additional services that no
    other services can provide; and, because of the many interactive features that most sites give, more and more people are being enticed
    to try it out. This first set of homemade spy gadgets
    is directed at children and contains projects that can
    be easily made by kids with minimal parental supervision.
    If you have chosen to work through a studio, I suggest you check out Havyn Studios.

  6. WWE Immortals cheat Says:

    Appreciation to my father who told me concerning this webpage, this blog is genuinely amazing.

  7. travel journal Says:

    What’s up, after reading this amazing piece of writing
    i am as well happy to share my experience here with mates.

Leave a comment

You must be logged in to post a comment.

a Freelance Web Developer is proudly powered by WordPress
Entries (RSS) and Comments (RSS).

Creative Commons License
Fernando Guillen's blog by Fernando Guillen is licensed under a Creative Commons Attribution-NoDerivs 3.0 Unported License.