dynamic background - jQuery

Asked

Viewed 892 times

0

I’m testing a slide of images, I’m dynamically altering the background using jquery’s "css" function by changing the url("image path"); But I realized that every time there’s a switch, he lowers the image again. Do you have to leave the background already downloaded and use it without having to request it at all times? Don’t mind, it’s ugly. http://codepen.io/rogeralbinoi/pen/Hlpft?editors=101

this is the same working using the img tag instead of background: http://codepen.io/rogeralbinoi/pen/kbIDp

  • Check that the image headers are allowing it to be cached. In addition to what has already been answered, this is a factor to consider.

2 answers

2

Pure Javascript script for image editing.

<script type="text/JavaScript">
function MM_preloadImages() { 
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
</script>

What to call:

<body onload="MM_preloadImages('2.jpg','1.jpg')">

Example:

http://jsfiddle.net/gDGbz/1/

I already leave in the body calling an image that is great and if I were to do it in real time it would take to appear.

1


There are some ways to perform image Preload in the browser. You can only use CSS - but it leaves a bit of "dirt" in your code, because we need to put some tags to perform the upload.

<div id="preload1"></div>
<div id="preload2"></div>
...

#preload1{
    background:url('http://lorempixel.com/1366/590/fashion/2') no-repeat -9999px -9999px;
}
#preload2{
    background:url('http://lorempixel.com/1366/590/fashion/3') no-repeat -9999px -9999px;
}
...

You can also use Javascript:

imagem1 = new Image();
imagem1.src = "http://lorempixel.com/1366/590/fashion/2";
imagem2 = new Image();
imagem2.src = "http://lorempixel.com/1366/590/fashion/2";

Javascript can make things more sophisticated. Let’s use an array:

preload = [
    "http://lorempixel.com/1366/590/fashion/2",
    "http://lorempixel.com/1366/590/fashion/3",
    "http://lorempixel.com/1366/590/fashion/4"
    ];

imagens = [];

for(i in preload){

    imagens[i] = new Image();
    imagens[i].src = preload[i]; //carrega a imagem corresponte ao número


}
  • 1

    Very good! Thanks, I didn’t even remember I could do it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.