Thomson
Thomson

Reputation: 21714

Can I load an online javascript to current DOM and modify it a little before it is evaluated?

I could insert online javascript to the current DOM as below,

s = document.createElement('script');
s.src = 'http://url/script.js';
document.appendChild(s);

But Can I preload the script here and customize it a little before it is evaluatied? Is there any javascript could be used to do so?

EDIT: the last line in the above code shoudl be document.getElementsByTagName('head')[0].appendChild(s)

Upvotes: 0

Views: 83

Answers (2)

RobG
RobG

Reputation: 147523

You could use XHR to load it as text, modify it, then isert it as the content of a script element. It will not be executed until it is in the DOM.

Upvotes: 1

jfriend00
jfriend00

Reputation: 708146

You append script tags this way to the head object, not to the document object like this:

document.getElementsByTagName('head')[0].appendChild(s).  

And, when you load them this way, they will load asychronously and then execute as soon as they are loaded. You will not be able to mess with them before they execute. You can register to be notified when they are loaded and have successfully been executed, but can't control when they execute.

Upvotes: 1

Related Questions