[英]can't remove dynamically added scripts
我在javascript和樣式表后面附加了一個對子元素的引用,但是當不再使用它時,我想再次刪除它。
var head = document.getElementsByTagName('head')[0];
// We create the style
var style = document.createElement('link');
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", '_css/style.'+app+'.css');
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("src", '_scripts/_js/script.'+app+'.js');
// And the append the style
head.appendChild(style);
head.appendChild(script);
這就是我添加腳本的方式,並且效果很好。.但是我不知道如何再次從HTML的head標簽中刪除標簽。
有人知道如何再次從標頭標簽中刪除標簽嗎。我一直在Stackoverflow周圍搜索,但實際上似乎沒有人遇到這種問題,但是如果有人知道還有另一個問題在回答這個問題,請告訴我。
簡而言之, You Cant ,即使您刪除了scripts
標記,這些腳本仍在內存中,沒有任何刪除它們。
一種技巧是編寫一個腳本,該腳本標識其他腳本在做什么(添加事件,創建變量,函數等),然后中和它們
但是解決此問題的真正方法是將腳本編寫在一個閉包中 ,以便一旦程序控制超出范圍,便將其從內存中刪除。
您可能還想深入研究Require.js
您可以使用removeChild
刪除元素:
var head = document.getElementsByTagName('head')[0];
//removing them from the head, where you added them
head.removeChild(script);
head.removeChild(style);
然而:
因此, 刪除樣式/鏈接元素可能有一些用處 ,但刪除腳本元素沒有用處。
恐怕我們無法刪除腳本標簽。 即使刪除該腳本,該腳本也已執行並且不能撤消。
例如:在test.js文件中
window.Test = "aaa";
當我們引用此腳本時,瀏覽器將下載並自動執行文件中的所有語句。 當我們刪除腳本標簽時,語句已執行(窗口變量已經具有屬性Test)
document.getElementsByTagName('head')[0].removeChild(document.getElementsByTagName('head')[0].getElementsByTagName('script')[0]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.