Chestone
Chestone

Reputation: 564

How to dynamically load an off domain script that loads another script from the same domain

So the situation I am in involves loading a third party script with this code:

var newScript = document.createElement('script');
newScript.src = 'http://someotherDomain.com/foo.js';
newScript.type = 'text/javascript';

document.body.appendChild(newScript);

foo.js contains the code:

document.write (unescape("%3Cscript src='http://someotherDomain.com/bar.js' type='text/javascript'%3E%3C/script%3E"));

The issue is that the first code snippet will execute successfully and pull in foo.js, but after foo.js is fetched the contents are not executed. I thought that after a browser loads a new script it will parse and then run the containing code. This works if I put in foo.js on initial page load, but not afterwards. Am I missing something?

Upvotes: 1

Views: 126

Answers (1)

Chestone
Chestone

Reputation: 564

Answered by Sime Vidas in the comments:

document.write doesn't work after page load... Your first code block shows how to add scripts to the page - if you can, just use that method to load the second script from within the first script.

Upvotes: 1

Related Questions