DIV CSS 佈局教程網

重寫 document.write,讓廣告 JS 不再阻塞頁面
編輯:關於JavaScript     

無阻塞載入 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

既然廣告碼是第三方的、跨網域的、我們改不了內容,那就換個思路——在它執行期間把 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();

第一版的兩個短板

  1. 順序不可控。多個檔案同時載入,誰先回來誰先渲染,但我們常常需要保證首屏廣告先出現。
  2. 無法前置設定參數。像 Google AdSense 就必須先在頁面上設定 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();

使用上的現實提醒

  • 重寫全域的 document.write 是有風險的。載入期間若同一份文件裡有其他腳本也在用它,輸出會被導向廣告容器。務必縮短接管窗口,並在 finished 階段準時還原。
  • 佇列會犧牲並行度。串行保證順序,代價是總載入時間變長。若廣告之間沒有依賴關係,把它們分組並行會更快。
  • 首屏廣告慎用。延遲載入會讓廣告位置出現明顯的版面跳動(CLS)。替容器預留固定高度,是兼顧效能與體驗的必要動作。
  • 這套技法已屬歷史產物。今日主流做法是 <iframe sandbox> 隔離或使用各家 SDK 提供的非同步載入接口,能避開就別去改 document.write。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved