Home > Web Front-end > JS Tutorial > body text

Prevent memory leaks caused by dynamic loading of JavaScript_javascript tips

WBOY
Release: 2016-05-16 18:45:12
Original
949 people have browsed it

In order to release script resources, some additional processing is usually performed after returning.

Copy code The code is as follows:

script = document.createElement('script');
script.src =
'http://example.com/cgi-bin/jsonp?q=What is the meaning of life?';
script.id = 'JSONP';
script .type = 'text/javascript';
script.charset = 'utf-8';
// After the tag is added to the head, it will be 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 scritp tag, after assigning an ID, load the script (such as YUI get()), clear the tag after loading and callback. The problem is that when you clear these script tags, the browser simply removes the tag node.
Copy code The code is as follows:

var script = document.getElementById('JSONP');
script.parentNode.removeChild(script);

When the browser removes this tag node, it does not perform garbage collection on the JavaScript resources in the node, which means that the JavaScript resources in the node are removed. In addition to the label node, it is not enough. You have to manually clear the content of the script label node:
Copy the code 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 object pointed to by these properties.
//Delete it manually to avoid memory leaks.
for (var prop in script) {
delete script[prop];
}
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template