[轉]資源預先載入

來源:互聯網
上載者:User

標籤:

     資源預先載入可以提升使用者體驗,如果每次使用者開啟頁面都要載入圖片,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 = /*@[email protected]*/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/

[轉]資源預先載入

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.