無阻塞載入 JavaScript 是效能優化的基本功。一般的做法是把 script 標籤動態插入 DOM,加上 async,讓它不擋住頁面渲染:
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
這招碰上大部分第三方廣告腳本就會失效——檔案下載成功了,HTML 也回來了,廣告卻死活不出現。罪魁禍首是廣告碼裡的那句 document.write:
document.write('<img src="https://img.jb51.net/logo_small.gif" alt="Logo">');
document.write() 的設計前提是在頁面串流解析的過程中執行。一旦文件載入完成,再呼叫它,瀏覽器會隱式觸發 document.open(),把整個既有文件擦掉重新開始。而我們的腳本是在頁面載入完之後才異步插入的,此時 document.write 的輸出要嘛被丟棄、要嘛直接把頁面清光。
既然廣告碼是第三方的、跨網域的、我們改不了內容,那就換個思路——在它執行期間把 document.write 換成一個往指定容器塞 HTML 的函數,執行完再還原。
function LoadADScript(url, container, callback) {
this.dw = document.write; // 先存下原始的 write
this.url = url;
this.containerObj = (typeof container == 'string')
? document.getElementById(container) : container;
this.callback = callback || function(){};
}
LoadADScript.prototype = {
startLoad: function() {
var script = document.createElement('script'), _this = this;
if (script.readyState) { // IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
_this.finished();
}
};
} else { // 其他瀏覽器
script.onload = function() { _this.finished(); };
}
document.write = function(ad) { // 關鍵:改寫成往容器追加
_this.containerObj.innerHTML += ad;
};
script.src = _this.url;
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
},
finished: function() {
document.write = this.dw; // 還原
this.callback.apply();
}
};
呼叫方式:
var loadScript = new LoadADScript('ad.js', 'msat-adwrap', function(){
console.log('msat-adwrap');
});
loadScript.startLoad();
google_ad_client、google_ad_slot 等變數,腳本才能讀取。把任務排進佇列,一個完成才啟動下一個,同時在每個任務上開一個 init 掛鉤:
var loadScript = (function() {
var adQueue = [], dw = document.write;
function LoadADScript(url, container, init, callback) {
this.url = url;
this.containerObj = (typeof container == 'string')
? document.getElementById(container) : container;
this.init = init || function(){};
this.callback = callback || function(){};
}
LoadADScript.prototype = {
startLoad: function() {
var script = document.createElement('script'), _this = this;
_this.init.apply(); // 先執行前置設定
if (script.readyState) {
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
_this.startNext();
}
};
} else {
script.onload = function() { _this.startNext(); };
}
document.write = function(ad) { _this.containerObj.innerHTML += ad; };
script.src = _this.url;
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
},
startNext: function() {
adQueue.shift();
this.callback.apply();
if (adQueue.length > 0) {
adQueue[0].startLoad();
} else {
document.write = this.dw; // 全部跑完才還原
}
}
};
return {
add: function(adObj) {
if (!adObj) return this;
adQueue.push(new LoadADScript(adObj.url, adObj.container, adObj.init, adObj.callback));
return this;
},
execute: function() {
if (adQueue.length > 0) adQueue[0].startLoad();
}
};
})();
頁面側寫成宣告式的鏈式呼叫,可讀性也好得多:
loadScript
.add({ url: 'ad.js', container: 'msat-adwrap',
callback: function(){ console.log('msat-adwrap'); } })
.add({ url: 'ad2.js', container: 'msat-adwrap2',
callback: function(){ console.log('msat-adwrap2'); } })
.add({
url: 'https://pagead2.googlesyndication.com/pagead/show_ads.js',
container: 'msat-adwrap',
init: function() {
google_ad_client = "ca-pub-xxxxxxxxxxxxxxxx";
google_ad_slot = "0000000000";
google_ad_width = 250;
google_ad_height = 250;
},
callback: function(){ console.log('msat-adwrap3'); }
})
.execute();
finished 階段準時還原。<iframe sandbox> 隔離或使用各家 SDK 提供的非同步載入接口,能避開就別去改 document.write。