[英]How to conditionally include assets in the <head> with Angular
我正在構建一頁Angular應用程序。 其中一個視圖的內容取決於外部javascript庫。
我不想在網站的每個視圖中都包含此外部JS資源,而僅依賴於該視圖。
基於當前視圖有條件地包含代碼塊的最佳方法是什么?
如果有可能,我希望可以放入以下內容:
<script ng-if="view == 'view1'" type='text/javascript' src='http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js'></script>
因此,您應該在頁面中包含庫腳本。
然后在綁定到元素的指令中,需要對其進行初始化。
app.directive('unity', function () {
return {
link: function (scope, element, attrs) {
// element is jQuery object when jQuery.js is included in page
// before angular - or it is a jQLite object similar to a jQuery object
// config code
u.initPlugin(element[0], "web_ovar_beta.unity3d");
}
}
});
使用情況:
<div unity></div>
這可以輕松擴展以將屬性從控制器傳遞給指令
它是
<script ng-if="view == 'view1'" type='text/javascript' ng-src='http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js'></script>
這是您不想做的事情。 它不能保證腳本不會被加載兩次。 由於該腳本用於特定視圖,因此使其成為一次性解決服務
app.factory('unityResolver', function ($document, $rootScope, $q, $timeout) {
var deferred = $q.defer();
var script = angular.element('<script>')[0];
script.src = '...';
script.async = true;
script.onload = script.onreadystatechange = function () {
if (['loaded', 'complete', undefined].indexOf(script.readyState) < 0)
return;
script.onload = script.onreadystatechange = null;
deferred.resolve();
$rootScope.$apply();
}
script.onerror = function onerror() {
script.onerror = null;
deferred.reject();
$rootScope.$apply();
};
$timeout(onerror, 20000);
$document.find('head').append(script);
return deferred.promise;
});
並在view / route resolve
使用它。
您想要的又是不可能的。
如果需要,可以使Javascript包含一個javascript文件,但是,如果使用AJAX加載所需的內容,則將其保留在那里,無論如何都將花費相同的時間。 但是將文件加載到JavaScript后,您可以將其從HTML中刪除,但是JavaScript引擎仍將文件的內容加載到其中。
立即在您的瀏覽器(Chrome或FF中使用Firebug)檢查器中嘗試:打開一個新標簽並轉到about:blank
然后將下面的代碼放入控制台
var include = (function(){
// the reference to the script
var theScript;
return function (filename, status){
if(status == 'on'){
// adding a script tag
var head = document.getElementsByTagName('head')[0];
theScript= document.createElement('script');
theScript.src = filename;
theScript.type = "text/javascript";
head.appendChild( theScript )
}else{
// removing it again
theScript.parentNode.removeChild( theScript );
}
}
})();
取自onclick事件從<head>標記中刪除特定的<script>標記
然后在檢查員的控制台中
include("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", 'on')
現在檢查Elements,您將看到jQuery加載在頁面的head標記中。 並在控制台中輸入jQuery
,您將看到function (a,b){return new n.fn.init(a,b)}
然后在控制台中使用它
include("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", 'off')
並再次檢查“元素”標簽,腳本標記將消失。 但是回到控制台並再次鍵入jQuery
,您將看到function (a,b){return new n.fn.init(a,b)}
,即使您已卸載文件,也無法從中刪除執行的代碼記憶。
您有2個選擇,可以將另一個框架頁面加載到iFrame中,或者如果您想使用Anagular加載View,則只需將文件包含在頭部就可以了,然后在加載完成后將其刪除
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.