我有一个包含很多页面的网站,它还有一个样式表切换器,因此用户可以选择自己定制的图形和布局(css 文件)
这些 css 文件在图形中下载,但仅在单击调用时...即使页面已经打开几秒钟或几分钟,此时图形可能已经加载以进行即时切换。
所以我实现了以下代码:
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];}}
}
</SCRIPT>
<body onLoad="MM_preloadImages('/corporate/heading.png','/creative/heading.png','/earth/heading.png','/under-the-sea/heading.png','/space-and-stars/heading.png','/classical/heading.png','/corporate/document.jpg','/space-and-stars/document.png','/creative/document.jpg','/earth/background.jpg','/under-the-sea/background.jpg','/classical/document.png','/classical/background.jpg','/under-the-sea/document.png','/corporate/home-graphics.png','/earth/content.jpg','/earth/footer.jpg','/earth/home-graphics.png','/under-the-sea/home-graphics.png','/creative/home-graphics.png','/space-and-stars/background.jpg','');">
它的效果非常好 - 打开页面,只要注意到可以单击样式的位置,就可以立即轻松地为样式切换缓存样式。
但是,该网站已经发展壮大,现在有相当多的页面在每个 html 文件中都有上述内容。我刚刚添加了一个“创意 2”样式,这导致上面需要更新.......此代码的维护效率低下,无法编辑每个页面。
所以我一直在寻找如何从外部页面调用数组,但没有得到以下工作并且我不知道足够的 JavaScript 来诊断原因。
在头部:
<script>
LoadStyles = function(pageName){
var head= document.getElementsByTagName('head')[0]; // get head element
var script= document.createElement('script'); // create new script element
script.type= 'text/javascript'; // set type
script.onreadystatechange= function () {
if (this.readyState == 'complete')
MM_preloadImages(imgArray) ; // call when script is loaded
}
script.src= pageName; // set script source path
head.appendChild(script); // append to body
}
</script>
带页面路径的正文加载:
<body onLoad="LoadStyles('/js/styles-code.js');">
样式代码.js...
imgArray = [
'/corporate/background.jpg',
'/creative/background.jpg',
'/earth/background.jpg',
'otherresourcenames.jpg'];
请问有比我指出的更多经验和知识的人这里有什么地方看起来不合适吗?
非常感谢
将
最佳答案
使用 apply 将字符串作为参数传递给 MM_preloadImages 函数,而不是将数组作为唯一参数传递给函数。
var imgArray = [
'/corporate/background.jpg',
'/creative/background.jpg',
'/earth/background.jpg',
'otherresourcenames.jpg'
];
MM_preloadImages.apply(this, imgArray);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply
关于javascript - 如何调用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7372048/