Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split JavaScript code into multiple files and use them without including them via script tag in HTML?

Tags:

javascript

I am making use of constructors (classes) extensively and would like each constructor to be in a separate file (something like Java). Suppose I have constructors say Class1, Class2, ... Class10 and I only want to use Class1 and Class5 I need to use script tags to include Class1.js and Class2.js into the HTML page. Later if I also need to use Class3 and Class6 I again need to go to the HTML page and add script tags for them. Maintenance with this approach is too poor.

Is there something in JavaScript similar to include directive of C? If not, is there a way to emulate this behavior?

like image 485
Cracker Avatar asked Jun 03 '11 12:06

Cracker


People also ask

How do I separate JavaScript files?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can I write JavaScript both within HTML and also as a separate file?

When working with files for the web, JavaScript needs to be loaded and run alongside HTML markup. This can be done either inline within an HTML document or in a separate file that the browser will download alongside the HTML document.

Can JavaScript be in a separate file give details?

You can keep JavaScript code in a separate file and then include it wherever it's needed, or you can define functionality inside HTML document itself.

Should I separate JavaScript from HTML?

You should put your JS code in a separate file because this makes it easier to test and develop. The question of how you serve the code is a different matter. Serving the HTML and the JS separately has the advantage that a client can cache the JS.


2 Answers

You can use jQuery.getScript:

http://api.jquery.com/jQuery.getScript

Or any of the many javascript loaders like YUI, JSLoader, etc. See comparison here:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

like image 128
Milimetric Avatar answered Sep 19 '22 12:09

Milimetric


You can use something like this:

jsimport = function(url) {
    var _head = document.getElementsByTagName("head")[0];         
    var _script = document.createElement('script');
    _script.type = 'text/javascript';
    _script.src = url;
    _head.appendChild(_script);
}

then use it in your code like:

jsimport("example.class.js");

Be careful to use this when the head is already in the DOM, else it won't work.

like image 31
aorcsik Avatar answered Sep 18 '22 12:09

aorcsik