While creating and inserting DOM element's, it seems that the functions used for the task are returning before the elements show in the page.
Before starting to insert the elements I set the display property of a div to 'block' and after inserting the elements I set the property to 'none', the problem is, the indicator is not showing in the page. It's possible to acplish this? Where $ is an alias for document.getElementById.
$('loading').className="visible";
var container = document.getElementById('container');
for(var i=0; i< 50000; i++){
var para = document.createElement('p');
para.appendChild(document.createTextNode('Paragraph No. ' + i));
container.appendChild(para);
}
$('loading').className="hidden";
It appears as createElement and/or appendChild run asynchronously, so I'm hiding the indicator almost immediately?
While creating and inserting DOM element's, it seems that the functions used for the task are returning before the elements show in the page.
Before starting to insert the elements I set the display property of a div to 'block' and after inserting the elements I set the property to 'none', the problem is, the indicator is not showing in the page. It's possible to acplish this? Where $ is an alias for document.getElementById.
$('loading').className="visible";
var container = document.getElementById('container');
for(var i=0; i< 50000; i++){
var para = document.createElement('p');
para.appendChild(document.createTextNode('Paragraph No. ' + i));
container.appendChild(para);
}
$('loading').className="hidden";
It appears as createElement and/or appendChild run asynchronously, so I'm hiding the indicator almost immediately?
Share Improve this question edited Dec 13, 2013 at 11:09 BenMorel 36.7k52 gold badges206 silver badges337 bronze badges asked Feb 2, 2009 at 2:33 CesarCesar 4,1368 gold badges47 silver badges69 bronze badges3 Answers
Reset to default 7setTimeout() is the answer. A simple 'one-line' change for you:
$('loading').className="visible";
setTimeout(function() {
var container = document.getElementById('container');
for(var i=0; i< 50000; i++){
var para = document.createElement('p');
para.appendChild(document.createTextNode('Paragraph No. ' + i));
container.appendChild(para);
}
$('loading').className="hidden";
}, 0);
I believe that the DOM won't refresh until after the script has finished running.
To make it run asynchronously, you could try wrapping it in a setTimeout
call, with a timeout of zero milliseconds. In pseudocode:
showLoadingIndicator();
setTimeout(addElements, 0);
function addElements() {
// perform your loop here
hideLoadingIndicator();
}
You never want anything to take too long in the browser. It kills the UI, including (unfortunately) animated gifs used as indefinite progress indicators.
The solution is to break the process up into, say, 50 calls with setTimeout() to a function that adds 1000 elements.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744783871a4593503.html
评论列表(0条)