Guesser
Guesser

Reputation: 1857

Load Javascript functions on window load dynamically

Is it possible to load the functions from separate Javascript files dynamically when a window loads, by setting an array and loader function?

Upvotes: 2

Views: 167

Answers (2)

J. K.
J. K.

Reputation: 8368

The easiest way is to simply add <script> elements to the DOM dynamically.

<script>
var scripts = [ 'a.js', 'b.js', ... ];
for (var i = 0; i < scripts.length; ++i) {
  document.write('<script src="' + scripts[i] + '"></' + 'script>');
}
</script>

Note that you can only do this before the DOMContentReady event is fired.

BTW event Google Closure Library uses this technique. And as a sidenote, you probably want to concatenate the scripts into a single file so that you save yourself (and your users) HTTP requests and get faster page loads.

What's cool about this is that the scripts are downloaded and evaluated right after the closing </script> tag so you don't have to wait for anything else before you can use them:

<!-- Let's pretend that a.js defines a function A() -->
<script>document.write('<script src="a.js"></' + 'script>');</script>
<script>
var a = new A();
</script>

Upvotes: 1

kieran
kieran

Reputation: 1537

Actually I may as well make this an answer rather than just a comment, require.js has exactly the functionality you're looking for, specifically look at this docs page to see it's use in-browser.

Upvotes: 0

Related Questions