Prevents Memory leakage caused by dynamic loading of JavaScript _ javascript skills

Source: Internet
Author: User
The Script tag can be used to load and run a JavaScript Script across domains. However, NeilFraser previously pointed out that resources are not released after the Script is run, even after the Script tag is removed. In order to release the script resources, additional processing is usually required after the return.

The Code is as follows:


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 ';
// After the label is added to the head, it is automatically loaded and run.
Var head = document. getElementsByTagName ('head') [0];
Head. appendChild (script)


In fact, many popular JS libraries use this method to create a scrui tag, assign an ID to it, load the script (such as YUI get (), and clear the tag after loading and callback. The problem is that when you clear these script tags, the browser only removes the tag node.

The Code is as follows:


Var script = document. getElementById ('jsonp ');
Script. parentNode. removeChild (script );


When the browser removes the tag node, it does not recycle the JavaScript Resources in the node. This means that it is not enough to remove the tag node. You must manually clear the content of the script tag node:

The Code is as follows:


// Remove any old script tags.
Var script;
While (script = document. getElementById ('jsonp ')){
Script. parentNode. removeChild (script );
// The browser will not recycle the objects pointed to by these properties.
// Manually delete it to avoid Memory leakage.
For (var prop in script ){
Delete script [prop];
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.