[轉]資源預加載

     資源預加載能夠提高用戶體驗,若是每次用戶打開頁面都要加載圖片,js,css等資源,會影響用戶體驗。資源預加載能夠必定程度上改善這種狀況。javascript

咱們能夠作的是,但第一個頁面load完的時候,在用戶閱讀網頁的空隙,把下一個頁面所用的資源提早加載過來cache住,這樣下個頁面就直接讀緩存資源了,這樣能夠必定程度改善用戶體驗。php

     那麼預加載資源須要解決的主要問題是JS加載過來不會被直接執行,css加載過來不會更改頁面樣式。css

這樣就會產生不少方案, 這裏介紹一種不錯的兼容方案:java

1. IE下用new Image()來加載瀏覽器

2. 其他瀏覽器使用object元素來加載緩存

緣由app

  • 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.

【程序源碼】ide

複製代碼
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'
    ]);
}
複製代碼

 

 

【相關連接】post

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

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

http://headjs.com/

相關文章
相關標籤/搜索