Dennis D
Dennis D

Reputation: 1343

Using Javascript to load other external Javascripts

I have a library of JS code to load from a folder. Instead of typing the <script src='...'></script> lines one by one in the tag of the HTML document, is there a way of just link one Javascript file which organizes and automatically load other javascript files.

I know the Dojotoolkit is using this technique where only one JS file is loaded onto the client's computer, and once the code has been requested in the browser, 20 other JS code each with <script> tag are generated.

Upvotes: 3

Views: 3196

Answers (3)

Zerstoren
Zerstoren

Reputation: 126

Try use requireJs, he have very userful functions

Official website

Upvotes: 0

balupton
balupton

Reputation: 48709

This is the code you need:

    // Create
    var bodyEl = document.body;
    var scriptEl = document.createElement('script');
    scriptEl.type = 'text/javascript';
    scriptEl.src = url;
    bodyEl.appendChild(scriptEl);

Put that into a function, have an array of all the javascript files, and call that function for each file.

Benefits of using the DOM is that document.write doesn't work in some funny instances. More about this here: document.write() vs inserting DOM nodes: preserve form information?

Code taken from the open source project jQuery Sparkle: http://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/jquery.appendscriptstyle.js#L103

Upvotes: 5

user333306
user333306

Reputation:

A simple way to do that:

document.write("<script type='text/javascript' src='b.js'></script>"); 

Upvotes: 1

Related Questions