Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there something similar to @import in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?

share|improve this question
18  
6  
@Daniel, I do not want to use an AJAX call. –  Alec Smart Jun 4 '09 at 12:02
2  
Nonetheless the answers are the same. –  annakata Jun 4 '09 at 12:20

36 Answers 36

function include(js)
{
    document.writeln("<script src=" + js + "><" + "/script>");
}
share|improve this answer
2  
Because if the page is already done loading when it is executing, or if it is executed because of a user action, then it will clear the page first. –  SevenBits Oct 20 '13 at 11:56

I also wrote a JavaScript dependency manager for Java web applications: JS-Class-Loader.

share|improve this answer

In case you are using Web Workers and want to include additional scripts in the scope of the worker, the other answers provided about adding scripts to the head tag etc will not work for you.

Fortunately, Web Workers have their own importScripts function which is a global function in the scope of the Web Worker, native to the browser itself as it is part of the spec.

Alternatively, as the second highest voted answer to your question highlights, RequireJS can also handle including scripts inside a Web Worker (likely calling importScripts itself but with a few other useful features).

share|improve this answer

There are a lot of potential answers for this questions. My answer is obviously based on a number of them. Thank you for all the help. This is what I ended up with after reading through all the answers.

The problem with $.getScript and really any other solution that requires a callback when loading is complete is that if you have multiple files that use it and depend on each other you no longer have a way to know when all scripts have been loaded. (Once they are nested in multiple files.)

ex:

file3.js

var f3obj = "file3";
//define other stuff

file2.js:

var f2obj = "file2";
$.getScript("file3.js", function(){

   alert(f3obj);

   // use anything defined in file3.
});

file1.js:

$.getScript("file2.js", function(){
   alert(f3obj); //This will probably fail because file3 is only guaranteed to have loaded inside the callback in file2.
   alert(f2obj); 


   // Use anything defined in the loaded script...
});

You are right when you say that you could specify ajax to run synchronously or use XMLHttpRequest, but the current trend appears to be to deprecate synchronous requests, so you may not get full browser support now or in the future.

You could try to use $.when to check an array of deferred objects, but now you are doing this in every file and file2 will be considered loaded as soon as the $.when is executed not when the callback is executed so file1 still continues execution before file3 is loaded. This really still has the same problem.

I decided to go backwards instead of forwards. Thank you document.writeln. I know its taboo, but as long as it is used correctly this works well. You end up with code that can be debugged easily, shows in the DOM correctly and can ensure the order the dependencies are loaded correctly.

You can of course use $("body").append(), but then you can no longer debug correctly anymore.

NOTE: you must use this only while the page is loading, otherwise you get a blank screen. In other words, always place this before / outside of document.ready. I have not tested using this after the page is loaded in a click event or anything like that, but pretty sure it'll fail.

I liked the idea of extending JQuery, but obviously you don't need to.

Before calling document.writeln, it checks to make sure the script has not already been loading by evaluating all the script elements.

I assume that a script is not fully executed until its document.ready event has been executed. (I know using document.ready is not required, but many people use it, handling this is a safeguard.)

When the additional files are loaded the document.ready callbacks will get executed in the wrong order. To address this when a script is actually loaded, the script that imported it is re-imported itself and execution halted. This causes the originating file to now have it's document.ready callback executed after any from any scripts that it imports.

Instead of this approach you could attempt to modify the JQuery readyList but this seemed like a worse solution.

solution:

$.extend(true,
{
    import_js : function(scriptpath, reAddLast)
    {
        if (typeof reAddLast === "undefined" || reAddLast === null) 
        { 
            reAddLast = true; // default this value to true. It is not used by the end user, only to facilitate recursion correctly.
        }

        var found = false;
        if (reAddLast == true) // If we are re-adding the originating script we do not care if it has already been added.
        {
            found = $('script').filter(function () {
                return ($(this).attr('src') == scriptpath);
            }).length != 0; //JQuery to check if the script already exists. (replace it with straight js if you don't like JQuery.
        }

        if (found == false) {

            var callingScriptPath = $('script').last().attr("src"); //Get the script that is currently loading. Again This creates a limitation where this should not be used in a button, and only before document.ready.

            document.writeln("<script type='text/javascript' src='" + scriptpath + "'></script>"); //Add the script to the document using writeln


            if (reAddLast)
            {
                $.import_js(callingScriptPath, false); // call itself with the originating script to fix the order.
                throw 'readding script to correct order: ' + scriptpath + ' < ' + callingScriptPath; // this halts execution of the originating script since it is getting reloaded. if you put a try / catch around the call to $.import_js you results will vary.
            }



            return true;
        }
        return false;
    }
});

usage:

file3:

var f3obj = "file3";
//define other stuff
$(function(){
   f3obj = "file3docready"; 
});

file2:

$.import_js('js/file3.js');
var f2obj = "file2";
$(function(){
   f2obj = "file2docready";  
});

file1:

$.import_js('js/file2.js');

//use objects from file2 or file3
alert(f3obj); // "file3"
alert(f2obj); // "file2"

$(function(){
    //use objects from file2 or file3 some more.
   alert(f3obj); //"file3docready"
   alert(f2obj); //"file2docready"
});
share|improve this answer

Keep it nice, short, simple, and maintainable! :]

// 3rd party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
    FULL_PATH + 'plugins/script.js'      // Script example
    FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library 
    FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
    FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
];

function load(url)
{
    var ajax = new XMLHttpRequest();
    ajax.open('GET', url, false);
    ajax.onreadystatechange = function ()
    {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4)
        {
            switch(ajax.status)
            {
                case 200:
                    eval.apply( window, [script] );
                    console.log("library loaded: ", url);
                    break;
                default:
                    console.log("ERROR: library not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

 // initialize a single load 
load('plugins/script.js');

// initialize a full load of scripts
if (s.length > 0)
{
    for (i = 0; i < s.length; i++)
    {
        load(s[i]);
    }
}

This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.

share|improve this answer

I am adding the statement you have mentioned in the top of my .js file:

document.write('<scr'+'ipt type="text/javascript" src="file2.js" ></scr'+'ipt>');

You don't need an include. You can just add the code to the existing JavaScript file. Or you can call JavaScript files from the HTML file.

share|improve this answer

protected by NullPoiиteя Jun 10 '13 at 5:07

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.