Question

So on my site there is a Javascript function that will load a new site from the server via XMLHttpRequest. After that it replaces the current page with the new one:

var post = new XMLHttpRequest();
post.open('POST', data);
post.onload = function() {
    var do = document.open("text/html", "replace");
    do.write(post.responseText);
    do.close();
    goOn();
}

function goOn() {
    console.log($('img:visible'));
}

Some could assume that after do.close() the document has changed and is ready. But it is not, e.g. if i load very much/big data/responseText the function goOn() only logs an empty result. Obviously goOn() gets in that case called before the DOM is ready to be read! Unfortunately the is no "ready" event fired after write() finished.... How can i be sure it is finished?

/EDIT: goOn() logs this to Chrome Console:

[prevObject: p.fn.p.init[1], context: #document, selector: "img:visible"]
context: #document
length: 0
prevObject: p.fn.p.init[1]
selector: "img:visible"
__proto__: Object[0]

But if i right after that type $('img:visible') into console manually it shows me all images....

Was it helpful?

Solution

did you try to attach a ready event to your document you can try something like below,

var post = new XMLHttpRequest();
post.open('POST', data);
post.onload = function() {
    var do = document.open("text/html", "replace");
    $(do).ready(function () { goOn(); });
    do.write(post.responseText);
    do.close();

}

function goOn() {
    console.log($('img:visible'));
}

EDIT:

Yes I tried on fiddler but there is JS event for that like below and here

var docx = document.open();
docx.onreadystatechange = function () { alert(this.readyState) };
alert(docx);
docx.write("<div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div><div>test test test test ttetst <br /></div>");

docx.close();​

after that just check the ready state and do your stuff when it complete.

I think this one ll do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top