最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is this the right way to preload images? - Stack Overflow

programmeradmin3浏览0评论

Is this below the right way to preload images?

I have a table which changes background once a 'select option' is changed. In the body of my page, I have this:

 <body onload="preload();">

And in my Form on the same page I have:

 <select onchange="swap();"><option bla bla></select>

And the js:

 function preload(){
 pic = new image(720, 65);
 pic.src = '../picture.jpg';
 }
 function swap(){
 document.getElementById("table_id_here").style.backgroundImage = '../picture.jpg';
 }

In the function swap() I guess the picture.jpg file is already preloaded, is that right?

Is there any way to check if the image has actually been cached (preloaded)?

Is this below the right way to preload images?

I have a table which changes background once a 'select option' is changed. In the body of my page, I have this:

 <body onload="preload();">

And in my Form on the same page I have:

 <select onchange="swap();"><option bla bla></select>

And the js:

 function preload(){
 pic = new image(720, 65);
 pic.src = '../picture.jpg';
 }
 function swap(){
 document.getElementById("table_id_here").style.backgroundImage = '../picture.jpg';
 }

In the function swap() I guess the picture.jpg file is already preloaded, is that right?

Is there any way to check if the image has actually been cached (preloaded)?

Share Improve this question edited Oct 3, 2019 at 9:28 Dale K 27.6k15 gold badges58 silver badges83 bronze badges asked Dec 2, 2009 at 11:05 user188962user188962
Add a ment  | 

3 Answers 3

Reset to default 3

Load the image with CSS either by using a sprite or by using display:none to hide it. A bit less to do on the js front then.

Use something like Firebug's network tool to check if those images are loaded.


(source: getfirebug.)

I guess your codes should work, anyway this is a popular script used by Dreamweaver for image preloading:

function MM_preloadImages() { //v3.0
  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];}}
}

MM_preloadImages('img1.gif','img2.gif'); //add more if required

The word "image" should be capitalized in the second line of your preload function, like this:

pic = new Image(720, 65);

Remember that you're creating a new Image object by calling its constructor -- that's what loads it in the browser.

So if it's not capitalized, you're invoking a separate function that may or may not exist.

发布评论

评论列表(0)

  1. 暂无评论