Heim  >  Artikel  >  Web-Frontend  >  预加载css或javascript的js代码_javascript技巧

预加载css或javascript的js代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:28:501027Durchsuche

预加载文件一般有两种常用的方式:xhr和动态插入节点的方式。动态插入节点是最为简单也最为广泛的一种异步加载方式(例如yui的Get模块),然后使用动态插入节点方法加载的文件都会在加载后立即执行,javascript的执行一方面会占用浏览器js执行进程,另一方面也可能改变页面结构,而css的执行更有可能让整个页面变化。xhr方式虽然不会执行脚本,但是由于同域的限制,且如今网站的静态文件都是部署在cdn服务器上,如何预加载css js文件也变有点玄妙了。

Stoyan Stefanov 撰文简明的阐述了一种加载文件而不会让之执行的方法。原文可见 http://www.phpied.com/preload-cssjavascript-without-execution/

具体的方法是,ie中使用 new Image().src 去预加载文件,而其他浏览器使用动态插入的 标签来完成加载。
部分代码如下

复制代码 代码如下:

window.onload = function () {

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

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

for (i = 0, max = preload.length; i
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);
}
};

demo 可见 http://phpied.com/files/object-prefetch/page1.php?id=1

几点说明:
1. new Image().src 之所以不能在ff中使用是因为ff对图片实现了一套单独的缓存。 同时safari和chrome看起来也没有被缓存。

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

3. ie7 ie8 也可以通过一些代码使用动态object加载文件(代码注释中有提到)。但是作者发现object 通常会消耗很大, so...


通过自身的实验发现相当不错的,有需求的同学不妨一试。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn