I have a script that takes 18 seconds to complete because it’s populating about 300 DIVs with HTML data. Code below:
HTML:
<div id="window">
<div id="wall">
<div class="module">
<div>
<div class="face front"></div>
<div class="face back"></div>
</div>
</div>
</div>
</div>
Javascript:
for (i = 0; i < numModules-1; ++ i)
{
var $mod = $('.module:eq(0)').clone();
modLeft += modSize;
if (modLeft + modSize > $('#wall').width())
{
modLeft = 0;
modTop += modSize;
}
$mod.css({
left: modLeft,
top: modTop
}).appendTo('#wall');
}
$.getJSON('html_server.php?callback=?', function(data) {
var htmlCount = data.length;
for (i = 0; i < numModules /* 300 or more */; ++ i)
{
var pick = Math.floor(Math.random() * Math.floor(htmlCount/2)) * 2;
var contentFront = data[pick];
var contentBack = data[pick+1];
var modStyle = '';
var $mod = $('.module:eq(' + i + ')');
var $modFront = $mod.find('.front');
var $modBack = $mod.find('.back');
// Set HTML content on front & back of module
$modFront.html(contentFront);
$modBack.html(contentBack);
}
});
If I comment out the two .html() calls, run time drops to about 110ms, so those are clearly the culprits. And the HTML content is not a ton, maybe 300 bytes of data at most.
Any advice?
EDIT: Added code that creates the DIVs. Perhaps I could move that within the getJSON callback and just drop in the HTML as they’re created? Would that help?
I created
moduleas a template and replaced the content with the response. And Moved your html logic below the JSON so it can done once. See below,