萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 非同步腳本載入器實現:支援多檔案依賴與回呼通知

現代前端專案常需動態載入多個第三方腳本(如分析、廣告、地圖 SDK),並需在全部載入完成後統一初始化。本文實現一個輕量級 Loader 類別,支援並行載入、狀態追蹤、完成回呼,採用原生 script.async 與 load 事件,無外部依賴。

完整實現代碼

var Loader = function () {};

Loader.prototype = {
  // 進入點:傳入腳本 URL 陣列與完成回呼
  require: function (scripts, callback) {
    this.loadCount = 0;
    this.totalRequired = scripts.length;
    this.callback = callback;

    for (var i = 0; i < scripts.length; i++) {
      this.writeScript(scripts[i]);
    }
  },

  // 每個腳本載入完成觸發
  loaded: function (evt) {
    this.loadCount++;
    if (this.loadCount === this.totalRequired && typeof this.callback === 'function') {
      this.callback.call();
    }
  },

  // 建立並插入 script 標籤
  writeScript: function (src) {
    var self = this;
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;                 // 關鍵:非同步載入,不阻塞渲染
    s.src = src;
    s.addEventListener('load', function (e) {
      self.loaded(e);
    }, false);
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(s);
  }
};

使用範例

var loader = new Loader();
loader.require([
  "https://cdn.example.com/analytics.js",
  "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY",
  "https://cdn.example.com/chat-widget.js"
], function() {
  // 所有腳本載入完成,安全初始化
  console.log('All Scripts Loaded');
  initAnalytics();
  initMap();
  initChat();
});

關鍵設計細節

細節說明
s.async = true告訴瀏覽器「不阻塞 HTML 解析,下載完立即執行」,多腳本並行下載,順序不保證。
計數器同步loadCount / totalRequired 確保所有腳本完成才觸發回呼,避免競態條件。
callback.call()保證回呼在正確上下文執行(此處為 Loader 實例)。
錯誤處理缺失原版未處理 error 事件,生產環境建議補上超時與失敗重試邏輯。

生產環境增強版(含錯誤處理與超時)

Loader.prototype.writeScript = function (src) {
  var self = this;
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.async = true;
  s.src = src;

  var timer = setTimeout(function() {
    s.removeEventListener('load', onLoad);
    console.error('Script load timeout:', src);
    self.loaded({ type: 'error', target: s }); // 視為完成避免死等
  }, 10000); // 10 秒超時

  function onLoad(e) {
    clearTimeout(timer);
    self.loaded(e);
  }
  s.addEventListener('load', onLoad, false);
  s.addEventListener('error', function(e) {
    clearTimeout(timer);
    console.error('Script load error:', src);
    self.loaded(e);
  }, false);

  document.head.appendChild(s);
};

現代替代方案

  • ES Modules 動態匯入:Promise.all([import('/a.js'), import('/b.js')]).then(init)(需模組化建構)。
  • RequireJS / SystemJS:完整 AMD/UMD 模組載入器,適合大型遺產專案。
  • Webpack/Code Splitting:建構時期靜態分析,import() 自動代碼分割,現代框架標配。

這個 Loader 適合輕量頁面、第三方 SDK 整合、或無建構工具的舊專案快速接入。

copyright © 萬盛學電腦網 all rights reserved