Home >Web Front-end >JS Tutorial >JavaScript asynchronous innerHTML usage analysis_javascript skills

JavaScript asynchronous innerHTML usage analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:38:211685browse

Of course, this time-sharing loading technology is only an auxiliary technology and does not have the ability to add nodes. Nowadays, another more peculiar technology Asynchronous innerHTML has been developed again. I cannot help but praise that foreigners are very advanced in research in this area.

Copy code The code is as follows:

function asyncInnerHTML(HTML, callback) {
var temp = document.createElement('div'),
frag = document.createDocumentFragment();
temp.innerHTML = HTML;//The content to be added is placed here first.
(function(){
if(temp.firstChild) {
frag.appendChild(temp.firstChild);//Then move to the document fragment little by little
setTimeout(arguments.callee, 0) ;//Use asynchronous calls to piece together document fragments by yourself until the div nodes are emptied
} else {
callback(frag);//This is where the actual operation of inserting nodes is performed
}
})();
}

Advantages of this technology:
1. Use closures to solve the memory overflow problem of IE6
2. Use setTimeout(fn,0) The hack drags the operation out of the queue to prevent the browser from suspended animation
3. Use Document Fragment to reduce the number of renderings of the page
4. The callback node can be inserted using the DOM standard method (appendChild) (such as IE's table , innerHTML of tbody, tr, td and other tags are read-only)
Usage:
Copy code The code is as follows:

var htmlStr = '

...

...

. ..
';
asyncInnerHTML(htmlStr, function(fragment){
// You can treat 'fragment' as a regular node.
document.body.appendChild(fragment);
});

However, this method does not work in every browser when adding nodes to the table, and it has to be said that it is a big failure. It has been tested that IE8, IE6, and FF3.5 have rendering errors, but chrome, safari4, opera10, etc. can render the table perfectly. It is estimated that node loss occurs when IE8 and others transfer nodes to document fragments.

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

在FF3.5的firebug显示下,table新添加的节点,标签都丢失了。
flagment
在IE8的开发人员工具中,我们发现table新添加节点出错严重,见于IE一惯的表现,这是很正常的事!
flagment
相关演示可见无忧的贴子,发现这种方法不是最佳的插入动态内容的方法。
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