Reputation: 9833
I have a div
being populated through the $.load()
method upon click. I then make this div
append to body
as a pop-up (kind of like a modal popup). On each click, the content of the div
is changed.
It so happens that the whole populating mechanism takes around 1.5 to 2 seconds. There is no problem if I click just once. But if I click another time, the div
pops up with the old content and then within the next 500 milliseconds or so the new content is loaded. So the user gets to see both the old and new content which I want to avoid.
(1) The first thing that came to mind was to use a setTimeout()
function to run after 2 seconds.
$('div#temp').load('somepage.php');
setTimeout(function(){
html = $('div#temp').html();
}, 2000);
$('div#popup').html(html).appendTo('body');
This does the work but it's not reliable. There is no guarantee that the new content will be loaded within 2 seconds. It could take 3 or more seconds too. Hardcoding a value more than 2 seconds isn't good too as it seems like eternity.
(2) The next thing I tried was to use a while
loop by using the following:
var html = '';
$('div#temp').load('somepage.php');
html = $('div#temp').html();
while(html == '')
{
html = $('div#temp').html();
}
$('div#popup').html(html).appendTo('body');
In the end this works, but for some reason it hangs the browser for a good 8-10 seconds before popping up the div
So clearly, both the alternatives have some drawback or the other. I'm hoping there might be some other way around this which I'm not aware of?
Upvotes: 1
Views: 1019
Reputation: 340045
It sounds like you just need to erase the contents of the popup div (and maybe put a "loading..." message into it) before you start the AJAX call.
Also, use the completion callback parameter to .load
to trigger the subsequent update to the DOM.
$('#popup').html('loading...');
$.get('somepage.php', function(content) {
$('#popup').html(content);
});
You should never poll the DOM or otherwise put the JS interpreter into a "busy loop" - it'll make the browser unresponsive.
Upvotes: 1
Reputation:
Have you tried using the complete callback of $.load?
.load( url [, data ] [, complete(responseText, textStatus, XMLHttpRequest) ] )
$('div#temp').load('somepage.php',function(responseText){
$('div#popup').html(responseText).appendTo('body');
});
And if the old content is still showing before the new content you can hide the old content first. Then you would not really need a temp div to store the data.
$('div#popup').fadeOut(function(){
$('div#popup').load('somepage.php',function(){
$(this).fadeIn();
});
});
Upvotes: 2
Reputation: 66693
I suggest you popup the div only after the content has been loaded:
$.get('somepage.php', function(data) {
$('div#popup').html(data).appendTo('body');
});
Upvotes: 1