Search code examples
javascripthtmlcssxmlhttprequest

Can js wait until XHR fully loaded in HTML


I am noob designing for website HTML with bootstrap

I found HTML does not support html include, so I googled and found awesome js which makes me manage header.html separetely and import to main html

I use another js which is needed at header.html

And what I found is that the js starts before header.html XHR fully finished so it didnt apply to the imported header.html

So here I need to ask is that is there any ways I can use for js to wait until XHR which is called from another js fully loded?


Solution

  • You can use a function similar to $.ready in jQuery to call a function when the page is finished loading, I recommend this simple waitUntilReady function over jQuery though:

    <script>
    
      const checkElement = () => console.log(
        'div#checkIfLoaded:',
        document.getElementById('checkIfLoaded')
      );
      
      const waitUntilReady = (fn) => document.readyState === 'complete'
        // fire immediately if document ready
        ? fn()
        // otherwise fire on DOMContentLoaded
        : window.addEventListener(
            'DOMContentLoaded', 
            fn
        );
      
      // doesn't exist yet
      checkElement();
      
      // will wait until the page is loaded
      waitUntilReady(checkElement);
      
    </script>
    <div id="checkIfLoaded"></div>