JaPerk14
JaPerk14

Reputation: 1664

javascript dynamically creating script block

I have a question about inserting a dynamically created script with JavaScript.

This is the code I'm using:

  var body = document.getElementsByTagName('body')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'code.js';
  body.appendChild(script);

I usually place scripts at the bottom of the page, but if it's dynamically inserted like this, is there a way to ensure that the script is placed at the bottom of the page?

Upvotes: 2

Views: 2344

Answers (2)

user1377664
user1377664

Reputation:

There's a way to ensure that using Jquery. The code.js will be called after DOM is loaded and putted right before </body> tag:

$(function() {
var body = document.getElementsByTagName('body')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'code.js';
  body.appendChild(script);
});

Upvotes: 0

Bergi
Bergi

Reputation: 664929

If it's dynamically inserted like this, is there a way to ensure that the script is placed at the bottom of the page?

You already do that with body.appendChild(script); of course there might be other elements inserted after it later on.

However, as you are dynamically inserting the script, there is absolutely no need to ensure placing it at any certain location - it is loaded and executed asynchronously (neither blocking something nor waiting for something). You may place it anywhere in the document, and even remove it right away, it will not influence any load or execute behaviour.

Upvotes: 2

Related Questions