Home  >  Article  >  Web Front-end  >  A brief analysis of document.createDocumentFragment() and js efficiency_javascript skills

A brief analysis of document.createDocumentFragment() and js efficiency_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:29:501118browse

document.createDocumentFragment() is simply to save the use of DOM. Every JavaScript operation on the DOM will change the rendering of the page and re-refresh the entire page, which consumes a lot of time. To solve this problem, you can create a document fragment, attach all new nodes to it, and then add the contents of the document fragment to the document at once.
This is a simple test page I wrote:

Copy the code The code is as follows:





document.createDocumentFragment() test page






Once the node is added to document.body (or the node after it), the page will immediately reflect this change. For the first small program, there is no problem in running it, but the problem is that it calls document.body.appendChild() ten times, which causes a page refresh each time, which will produce a lot of page fragments. In the second piece of code, document.body.appendChild() is only called once, which means that the page only needs to be refreshed once, and the time required will obviously be less than the previous one.

I used three browsers to test the above test code, and the approximate results are:
IE7:
Method 1 time: 140
Method two time: 125

Firefox:
Method one time: 66
Method two time: 43

Chrome:
Time used for method one: 35
Time used for method two: 25
The results obtained are still consistent with the theory.
Statement:
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