资源预加载

      资源预加载可以提升用户体验,如果每次用户打开页面都要加载图片,js,css等资源,会影响用户体验。资源预加载可以一定程度上改善这种情况。

我们可以做的是,但第一个页面load完的时候,在用户阅读网页的空隙,把下一个页面所用的资源提前加载过来cache住,这样下个页面就直接读缓存资源了,这样可以一定程度改善用户体验。

     那么预加载资源需要解决的主要问题是JS加载过来不会被直接执行,css加载过来不会更改页面样式。

这样就会产生很多方案, 这里介绍一种不错的兼容方案:

1. IE下用new Image()来加载

2. 其余浏览器使用object元素来加载

原因

  • new Image().src doesn't do the job in FF because it has a separate cache for images. Didn't seem to work in Safari either where CSS and JS were requested on the second page where they sould've been cached
  • the dynamic object element has to be outside the head in most browsers in order to fire off the downloads
  • dynamic object works also in IE7,8 with a few tweaks (commented out in the code above) but not in IE6. In a separate tests I've also found the object element to be expensive in IE in general.

【程序源码】

function  preload(arr) {
    
var  i  =  arr.length,
    o,
    d 
=  document,
    b 
=  document.body,
    isIE 
=   /* @cc_on!@ */ 0 ;
    
while  (i -- ) {
        
if  (isIE) {
            
new  Image().src  =  arr[i];
            
continue ;
        }
        o 
=  d.createElement( ' object ' );
        o.data 
=  arr[i];
        o.width 
=  o.height  =   0 ;
        b.appendChild(o);
    }
}

window.onload 
=   function  () {
    preload([
        
' http://localhost/load.js ' ,
        
' http://localhost/load.css ' ,
        
' http://localhost/load.jpg '
    ]);
}

 

 

【相关链接】

http://www.phpied.com/preload-cssjavascript-without-execution/

http://www.phpied.com/the-art-and-craft-of-postload-preloads/

http://headjs.com/

转载于:https://www.cnblogs.com/bluedream2009/archive/2010/12/05/1897281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值