防止動態(tài)加載JavaScript引起的內(nèi)存泄漏問題
更新時間:2009年10月08日 18:06:32 作者:
利用Script標簽可以跨域加載并運行一段JavaScript腳本, 但Neil Fraser先前已指出,腳本運行后資源并沒被釋放,即使是Script標簽移除后。
為了釋放腳本資源,通常在返回后還要一些進行額外的處理。
script = document.createElement('script');
script.src =
'http://example.com/cgi-bin/jsonp?q=What+is+the+meaning+of+life%3F';
script.id = 'JSONP';
script.type = 'text/javascript';
script.charset = 'utf-8';
// 標簽加到head后,會自動加載并運行。
var head = document.getElementsByTagName('head')[0];
head.appendChild(script)
實際上很多流行的JS庫都采用這種方式,創(chuàng)建一個scritp標簽,賦予一個ID后加載腳本(比如YUI get()),加載完并回調(diào)后清除該標簽。問題在于當(dāng)你清除這些script標簽的時候,瀏覽器僅僅是移除該標簽結(jié)點。
var script = document.getElementById('JSONP');
script.parentNode.removeChild(script);
當(dāng)瀏覽器移除這標簽結(jié)點后的同時并沒對結(jié)點內(nèi)JavaScript資源的進行垃圾回收,這意味著移除標簽結(jié)點還不夠,還得手動的清除script標簽結(jié)點的內(nèi)容:
// Remove any old script tags.
var script;
while (script = document.getElementById('JSONP')) {
script.parentNode.removeChild(script);
// 瀏覽器不會回收這些屬性所指向的對象.
//手動刪除它以免內(nèi)存泄漏.
for (var prop in script) {
delete script[prop];
}
}
復(fù)制代碼 代碼如下:
script = document.createElement('script');
script.src =
'http://example.com/cgi-bin/jsonp?q=What+is+the+meaning+of+life%3F';
script.id = 'JSONP';
script.type = 'text/javascript';
script.charset = 'utf-8';
// 標簽加到head后,會自動加載并運行。
var head = document.getElementsByTagName('head')[0];
head.appendChild(script)
實際上很多流行的JS庫都采用這種方式,創(chuàng)建一個scritp標簽,賦予一個ID后加載腳本(比如YUI get()),加載完并回調(diào)后清除該標簽。問題在于當(dāng)你清除這些script標簽的時候,瀏覽器僅僅是移除該標簽結(jié)點。
復(fù)制代碼 代碼如下:
var script = document.getElementById('JSONP');
script.parentNode.removeChild(script);
當(dāng)瀏覽器移除這標簽結(jié)點后的同時并沒對結(jié)點內(nèi)JavaScript資源的進行垃圾回收,這意味著移除標簽結(jié)點還不夠,還得手動的清除script標簽結(jié)點的內(nèi)容:
復(fù)制代碼 代碼如下:
// Remove any old script tags.
var script;
while (script = document.getElementById('JSONP')) {
script.parentNode.removeChild(script);
// 瀏覽器不會回收這些屬性所指向的對象.
//手動刪除它以免內(nèi)存泄漏.
for (var prop in script) {
delete script[prop];
}
}
相關(guān)文章
JavaScript中字符串(string)轉(zhuǎn)json的2種方法
這篇文章主要介紹了JavaScript中字符串(string)轉(zhuǎn)json的2種方法,兩種方法分別是使用js函數(shù)eval()和、使用jquery.parseJSON()方法,需要的朋友可以參考下2015-06-06

