skip to Main Content

I got a page that loads several add-ons and I need to insert html element (script) just before body closing tag (</ body>) as last loading. I tried some javascript methods such as appendChild and insertAdjacentElement, but none seem to work because of loading other scripts.

What I have done so far and didn’t work:

Using appendChild or insertAdjacentElement got same result:

var myscript = document.createElement('script');
myscript.setAttribute('src','https://xxxxx/myscript.min.js');
myscript.async = true;
document.body.appendChild(myscript);  or  document.body.insertAdjacentElement('beforeend', myscript);

Result:

<body>
   <element1>
   <element2>
   *<myscript> <--- inserted here*
   <element3>
   <element4>
   <element5>
   <element6>
   <element7>
</body>

Expected result:

<body>
   <element1>
   <element2>
   <element3>
   <element4>
   <element5>
   <element6>
   <element7>
   *<myscript> <--- insert here*
</body>

enter image description here

2

Answers


  1. It looks like the javascript code might be executed before the html document is fully loaded. To avoid this place your javascript code inside a DOMContentLoaded to make sure the code runs after the DOM is fully loaded:

    document.addEventListener('DOMContentLoaded', function() {
       var myscript = document.createElement('myscript');
       myscript.setAttribute('src','https://xxxxx/myscript.min.js');
       myscript.async = true;
       document.body.appendChild(myscript);
    });
    
    Login or Signup to reply.
  2. seems to be working for me with append

    console shows the script element last of the body

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search