翻閱《JavaScript 高級程序設計》,站在巨人的肩膀上重新梳理動態腳本的加載與執行。
所謂動態 JS、動態樣式,指的是頁面初次加載時並不存在、而是後續通過 DOM 操作動態插入的腳本或樣式。它包含兩種形式:加載外部文件、添加內部代碼塊。有趣的是,動態加載的外部文件能夠立即執行,而動態添加的代碼塊卻未必能如願運行。下面以 JS 為例,逐一探討加載、執行,以及 jQuery 與 AngularJS 的處理方式。
由於動態加載的外部 JS 會立即執行,也沒有太多兼容性顧慮,這部分相對好處理。真正的難點在於:如何準確知道腳本已經加載完成?這就把老 IE 的兼容性問題引了出來。
// 動態加載外部 js 文件,參數:url、loaded、error
var AsyncScripts = (function () {
function load() {
var args = arguments;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.type = 'text/javascript';
js.src = args[0];
head.appendChild(js);
if (document.all) {
js.onreadystatechange = function () {
if (js.readyState == 'loaded' || js.readyState == 'complete') {
args[1] && args[1]();
}
};
} else {
js.onload = function () { args[1] && args[1](); };
}
js.onerror = function () { args[2] && args[2](); };
}
return { load: load };
})();
AsyncScripts.load('https://cdn.example.com/lib/jquery.js', function () { alert($); });
理論上 script.appendChild(createTextNode(codeStr)) 能正常運行,但在 IE 中,<script> 被視為特殊元素(<style> 同理),不允許 DOM 訪問其子節點。解法是改用 script.text 屬性指定代碼:
var AsyncScripts = (function () {
function execJSblock(scriptsStr) {
var script = document.createElement('script');
script.type = 'text/javascript';
if (document.all) {
script.text = scriptsStr;
} else {
script.appendChild(document.createTextNode(scriptsStr));
}
document.body.appendChild(script);
}
return { exec: execJSblock };
})();
AsyncScripts.exec('var a=1000;alert(document.body.clientWidth+";"+a)');
// 效果等同於 eval(scriptsStr)
動態加載樣式與加載 JS 思路一致,問題也基本相同,區別在於創建的是 style 或 link 而非 script:IE 下用 style.styleSheet.cssText,標準做法則是 style.appendChild(document.createTextNode(stylesStr))。此外要注意,link 標籤放在 head 中才有效,不像 script/style 可以寫在 body 裡。
在 jQuery 1.4.1 及更早版本中,通過 DOM 操作插入的腳本是不會執行的;這個問題從 1.4.2 起被修復。也就是說,下面這些代碼裡的 script 和 style 都會立即生效:
$(selector).append('<script>alert(1)</script>');
$(selector).html('<script>alert(1)</script>');
$(selector).append('<style>.a{color:red;}</style>');
在 Angular 裡,如果用 ng-bind="html string",Angular 會把內容當作純文本,而不像 jQuery 那樣執行其中的腳本;即便換成 ng-bind-html 也一樣不會執行。這正是 Angular 嚴謹之處——它提供了 $sce 服務(意為「嚴格上下文模式」)來處理這類場景。注入 $sce 後調用 trustAsHtml,再配合 ng-bind-html 即可:
['$scope','$sce',function($scope,$sce) {
$scope.trustHtml = function(_html) {
return $sce.trustAsHtml(_html);
};
}];
方便起見,還可以封裝成過濾器:
app.filter('trustHTML', ['$sce', function ($sce) {
return function (_html) {
return $sce.trustAsHtml(_html);
};
}]);
還有一個坑:動態添加的指令無法運行。因為 Angular 在頁面加載後會從 ng-app 開始搜集並編譯指令,動態插入的指令已不在其範圍內,此時需要調用 $compile 服務手動重新編譯:
link: function($scope, $element, $attrs) {
angular.element(DOMobj).html(_html);
$compile(angular.element(DOMobj).contents())($scope);
};
初學 AngularJS 的過程中,最大的感受是:它和 jQuery 是兩種思維方式下的產物。既然項目選用了 Angular,就該拋開大量命令式的 DOM 操作,改用聲明式的思路;即便需要操作 DOM,Angular 也有對應的做法,這時 jQuery 就可以退居幕後了。慢慢挖坑、慢慢填坑,收穫總在不經意間。