1

I would like to have the following on my page:

  1. a script ("script1.js") that adds a second script ("script2.js") dynamically to the page.
  2. a third script ("script3.js").

"script3" overwrites some of the functions in "script2", therefore the order that the scripts should be parsed is:

script1 > script2 > script3.

And the console should show: 1 2 3. Instead I see 1 3 2.

I have tried using "defer" on "script3" with no success:

HTML file:

<html>
<head>
    <script src="script1.js"></script>
    <script defer type='text/javascript' src="script3.js"></script>
</head>
</html>

script1.js:

console.log('1');
var head = document.getElementsByTagName('head')[0];
const url = 'script2.js';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);

script2.js:

console.log('2');

script3.js:

console.log('3');
4
  • If that's the exact code in script1, you could just include that as a script tag but I guess that's not an option here. A workaround would be to also dynamically load the third script, but depending on the amount of scripts that should be loaded after the second might make this unviable Commented Jan 20, 2018 at 12:59
  • Your workarounds do indeed work, but I would like the third script to be fixed in the HTML and the second to be loaded dynamically. Commented Jan 20, 2018 at 19:08
  • did you look at jQuery.getScript() or something like that where you can chain load the scripts? api.jquery.com/jQuery.getScript Commented Jan 20, 2018 at 19:13
  • jQuery is one of the scripts that is to be loaded dynamically. So solution has to be vanilla js/html. Commented Jan 20, 2018 at 20:25

1 Answer 1

1

As ugly as it sounds, you could use document.write inside script1.js to load script2.js. The scripts will execute in correct order.

// script1.js
console.log('1');
document.write('<script src="script2.js"></script>');
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm, can't believe I didn't try this before. I saw this mentioned on various other questions, but somehow overlooked it (security is not an issue in my case). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.