dynamic background - jQuery

0

I'm testing an image slide, I'm dynamically changing the background using the "css" function of jquery by changing the url ("image path"); But I realized that whenever there is the exchange, it lowers the image again. Do you have the background already downloaded and use it without having to make a request all the time? Do not call it, it's really ugly. link

This is the same with using the img tag instead of background: link

    
asked by anonymous 09.06.2014 / 19:26

2 answers

1

There are a few ways to preload images in the browser. You can use only CSS - but it leaves a bit of "dirt" on your code, as we need to put some tags to load.

<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


}
    
10.06.2014 / 16:25
2

Pure Javascript script to preload image.

<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>

How to call:

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

Example:

link

I leave the body calling an image that is large and if it were to do it in real time it would take time to show up.

    
10.06.2014 / 17:18