js 的延時載入

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   使用   sp   java   

最近,由於項目中引用到的指令碼比較多,頁面首次載入速度有些慢,於是進行了一些最佳化

用到的是延時載入技術,大概思路就是減少頁面的<script>標籤,並依靠lazyload.js延時載入相應的指令檔。

首先,要先引用lazyload.js ,這是一個老外寫的指令碼,我放到了公司的圖片伺服器上,大家可以直接存取  http://img.fang.com/rent/image/rent/js/lazyload.js

實踐之前,先來看一下它的使用文檔

// Load a single JavaScript file and execute a callback when it finishes.LazyLoad.js(‘http://example.com/foo.js‘, function () {  alert(‘foo.js has been loaded‘);});// Load multiple JS files and execute a callback when they‘ve all finished.LazyLoad.js([‘foo.js‘, ‘bar.js‘, ‘baz.js‘], function () { alert(‘all files have been loaded‘);});// Load a CSS file and pass an argument to the callback function.LazyLoad.css(‘foo.css‘, function (arg) { alert(arg);}, ‘foo.css has been loaded‘);// Load a CSS file and execute the callback in a different scope.LazyLoad.css(‘foo.css‘, function () { alert(this.foo); // displays ‘bar‘}, null, {foo: ‘bar‘});

可以看到,它同時支援js、css的延時載入。並且,還能一次載入多個檔案。
下面是我自己定義的返回js路徑的方法
// 用於返回延時載入的js路徑        function getJSUrls() {            var version = ‘<%=FileVision %>‘;            var mapimgurl = ‘<%=MapImgUrl %>‘;return [                               mapimgurl + ‘/SearchResultNew.js?v=‘ + version,                mapimgurl + ‘/suggestionnew.js?v=‘ + version,                mapimgurl + ‘/jquery.zclip.min.js?v=‘ + version,                               mapimgurl + ‘/ZUMAP.js?v=‘ + version,                mapimgurl + ‘/common.js?v=‘ + version            ];        }

mapimgurl是圖片伺服器的某一目錄,這裡設定成變數便於統一管理。getJSUrls方法返回的是一個字串數組,正好可以對應文檔中給出的第二種方法。

得到路徑之後,開始載入

     // 消極式載入        (function () {            LazyLoad.js(getJSUrls(), function () {              // do something            });        } ())   

這裡的得到getJSUrls返回的數組,還可以換一種方式處理

        var urls = getJSUrls();                for (var i = 0; i < urls.length; ++i) {          LazyLoad.js(urls[i], function(){                // do something            });        }                

這樣是一個一個的載入,可以根據情況加上一些判斷。

 

這隻是一個小小的嘗試,具體能最佳化多少,其實我也不知道。新手還在學習中,大家共勉~

 

js 的延時載入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.