天天看點

#yyds幹貨盤點#前端圖檔預加載

上一篇文章講了圖檔懶加載的兩種方法,今天再來講講圖檔預加載。

用css和JavaScript實作預加載

實作預加載圖檔有很多方法,包括使用css、JavaScript及兩者的各種組合。這些技術可根據不同設計場景設計出相應的解決方案,十分高效。

單純使用CSS,可容易、高效地預加載圖檔,代碼如下:

#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }  

#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }  

#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }
複制代碼      

将這三個ID選擇器應用到(X)html元素中,我們便可通過CSS的background屬性将圖檔預加載到螢幕外的背景上。

隻要這些圖檔的路徑保持不變,當它們在Web頁面的其他地方被調用時,浏覽器就會在渲染過程中使用預加載(緩存)的圖檔。簡單、高效,不需要任何JavaScript。

該方法雖然高效,但仍有改進餘地。使用該法加載的圖檔會同頁面的其他内容一起加載,增加了頁面的整體加載時間。

為了解決這個問題,我們增加了一些JavaScript代碼,來推遲預加載的時間,直到頁面加載完畢。代碼如下:

function preloader() {  

    if (document.getElementById) {  

        document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px";  

        document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px";  

        document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px";  

    }  

}  

function addLoadEvent(func) {  

    var oldonload = window.onload;  

    if (typeof window.onload != 'function') {  

        window.onload = func;  

    } else {  

        window.onload = function() {  

            if (oldonload) {  

                oldonload();  

            }  

            func();  

        }  

    }  

}  

addLoadEvent(preloader);      

在該腳本的第一部分,我們擷取使用類選擇器的元素,并為其設定了background屬性,以預加載不同的圖檔。

該腳本的第二部分,我們使用addLoadEvent()函數來延遲preloader()函數的加載時間,直到頁面加載完畢。

如果JavaScript無法在使用者的浏覽器中正常運作,會發生什麼?很簡單,圖檔不會被預加載,當頁面調用圖檔時,正常顯示即可。

使用Ajax實作預加載

window.onload = function() {  

    setTimeout(function() {  

        // XHR to request a js and a CSS  

        var xhr = new XMLHttpRequest();  

        xhr.open('GET', 'http://domain.tld/preload.js');  

        xhr.send('');  

        xhr = new XMLHttpRequest();  

        xhr.open('GET', 'http://domain.tld/preload.css');  

        xhr.send('');  

        // preload image  

        new Image().src = "http://domain.tld/preload.png";  

    }, 1000);  

};      
window.onload = function() {  

    setTimeout(function() {  

        // reference to <head>  

        var head = document.getElementsByTagName('head')[0];  

        // a new CSS  

        var css = document.createElement('link');  

        css.type = "text/css";  

        css.rel  = "stylesheet";  

        css.href = "http://domain.tld/preload.css";  

        // a new JS  

        var js  = document.createElement("script");  

        js.type = "text/javascript";  

        js.src  = "http://domain.tld/preload.js";  

        // preload JS and CSS  

        head.appendChild(css);  

        head.appendChild(js);  

        // preload image  

        new Image().src = "http://domain.tld/preload.png";  

    }, 1000); 

};      

繼續閱讀