Is this the right way to preload images?
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();">开发者_Python百科;<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)?
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.com)
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.
精彩评论