2

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

1
  • 2
    maybe take a look at require.js? Commented Nov 15, 2012 at 19:36

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

You can add script tags anytime, not just before DOMContentReady. You meant to say you can't use document.write after DOMContentReady. Just use DOM manipulation to add it.
Yep, that's what I meant. By "this", I meant document.write. Sorry for the confusion.
0

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.

Comments

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.