📜 ⬆️ ⬇️

Do not drive horses!

It takes time for the browser to build the DOM tree when the page loads. This should be considered when uploading content to the page using Ajax.
Actually what am I doing ...
When developing the last project, I took upon myself the task of organizing content uploading to the page using Ajax. The XMLHTTP connection was successfully established, I received the necessary content and using innerHTML inserted it into a hidden block on the page, in order to pull out the necessary parts from there. And then I stumbled upon a rake: in response to my requests getElementById or getElementsByTagName, the browser reported undefined instead of the loaded elements I needed.

As it turned out, the rake lurked in the fact that I was in too much of a hurry: from the moment the received content was inserted on the page and until the time it was accessed, the browser did not have time to add new elements to the DOM tree of the page. Solution: set a timeout, thus giving the browser time to build the DOM tree. And if we put a label node (for example, an empty div with id = 'flag') at the end of the downloadable content, we can determine if the browser has finished its work, or we need to wait a little more.
var hiddenDiv; //
var oXmlHttp = createXmlHttp();
oXmlHttp.open("get", url, true);
oXmlHttp.onreadystatechange = function ()
{
if (oXmlHttp.readyState == 4)
{
if (oXmlHttp.status == 200)
{
hiddenDiv.innerHTML = oXmlHttp.responseText;
var t = setTimeout("handle()", 100);
}
}
}
oXmlHttp.send(null);

function handle()
{
if (document.getElementById('flag') != undefined)
{
// DOM ,
}
else
{
var t = setTimeout("handle()", 100);
}
}

Depending on the size of the received content, you should set the required timeout.

Original article

')

Source: https://habr.com/ru/post/39496/


All Articles