前端优化--文件预加载

xhr和动态插入节点

使用动态插入节点方法加载的文件都会在加载后立即执行。

ie中使用 new Image().src 去预加载文件,而其他浏览器使用动态插入的 <object> 标签来完成加载。

window.onload = function () { 

var i = 0, 
max = 0, 
o = null, 

// list of stuff to preload 
preload = [ 
'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.png', 
'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.js', 
'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.css' 
], 
isIE = navigator.appName.indexOf('Microsoft') === 0; 

for (i = 0, max = preload.length; i < max; i += 1) { 

if (isIE) { 
new Image().src = preload[i]; 
continue; 


o = document.createElement('object'); 
o.data = preload[i]; 

// IE stuff, otherwise 0x0 is OK 
//o.width = 1; 
//o.height = 1; 
//o.style.visibility = "hidden"; 
//o.type = "text/plain"; // IE 
o.width = 0; 
o.height = 0; 

// only FF appends to the head 
// all others require body 
document.body.appendChild(o); 

}; 

动态插入的 object 标签需要插入到非 head部分,以触发加载

猜你喜欢

转载自blog.csdn.net/qq_40001322/article/details/80987907