Tell me more ×
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 a JavaScript file?

share|improve this question
12  
3  
@Daniel, I do not want to use an AJAX call. – Alec Smart Jun 4 '09 at 12:02
1  
Nonetheless the answers are the same. – annakata Jun 4 '09 at 12:20
7  
+1 for the Great Question badge. You're welcome. – anthony-arnold Nov 25 '11 at 5:45
2  
This is a great question. A Javascript file within a Javascript file!? JAVASCRIPTCEPTION! – Jordan Thornquest Apr 24 at 14:54
show 2 more comments

23 Answers

up vote 880 down vote accepted

There is no import / include / require in javascript, but there are two main ways to achieve what you want:

1 - You can load it with an AJAX call then use eval.

This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.

2 - Add a script tag with the script URL in the HTML.

Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the <script /> tag in the head of the web page, or at the bottom of the body.

Both of these solutions are discussed and illustrated here.

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

E.G : my_lovely_script.js contains MySuperObject

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function :

var myPrettyCode = function() {

   // here, do what ever you want

};

Then you run all that :

loadScript("my_lovely_script.js", myPrettyCode);

Ok, I got it. But it's a pain to write all this stuff.

Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :

$.getScript("my_lovely_script.js", function(){


   alert("Script loaded and executed.");
   // here you can use anything you defined in the loaded script

});
share|improve this answer
10  
Nope but somebody that uses something as advanced as Rhino or else wouldn't ask this question. – e-satis Jul 15 '10 at 3:53
24  
jquery FTW! thanks for that :) – javamonkey79 Feb 21 '11 at 6:47
67  
Holy crap. What an awesome answer. – Calvin Froedge Aug 14 '11 at 18:51
21  
Dawn it. I just want to take this way to load jquery.js :( – aXqd Dec 10 '11 at 12:28
14  
Just to be complete, there is a third way: In certain solutions when you control both javascript files, you can just make 1 giant javascript file which combines the content of both files. – Toad Sep 7 '12 at 8:36
show 11 more comments

I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/

// ----- USAGE -----

require('ivar.util.string');
require('ivar.net.*');
require('ivar/util/array.js');
require('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');

ready(function(){
    //do something when required scripts are loaded
});

    //--------------------

var _rmod = _rmod || {}; //require module namespace
_rmod.LOADED = false;
_rmod.on_ready_fn_stack = [];
_rmod.libpath = '';
_rmod.imported = {};
_rmod.loading = {
    scripts: {},
    length: 0
};

_rmod.findScriptPath = function(script_name) {
    var script_elems = document.getElementsByTagName('script');
    for (var i = 0; i < script_elems.length; i++) {
        if (script_elems[i].src.endsWith(script_name)) {
            var href = window.location.href;
            href = href.substring(0, href.lastIndexOf('/'));
            var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);
            return url.substring(href.length+1, url.length);
        }
    }
    return '';
};

_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library


_rmod.injectScript = function(script_name, uri, callback, prepare) {

    if(!prepare)
        prepare(script_name, uri);

    var script_elem = document.createElement('script');
    script_elem.type = 'text/javascript';
    script_elem.title = script_name;
    script_elem.src = uri;
    script_elem.async = true;
    script_elem.defer = false;

    if(!callback)
        script_elem.onload = function() {
            callback(script_name, uri);
        };

    document.getElementsByTagName('head')[0].appendChild(script_elem);
};

_rmod.requirePrepare = function(script_name, uri) {
    _rmod.loading.scripts[script_name] = uri;
    _rmod.loading.length++;
};

_rmod.requireCallback = function(script_name, uri) {
    _rmod.loading.length--;
    delete _rmod.loading.scripts[script_name];
    _rmod.imported[script_name] = uri;

    if(_rmod.loading.length == 0)
        _rmod.onReady();
};

_rmod.onReady = function() {
    if (!_rmod.LOADED) {
        for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){
            _rmod.on_ready_fn_stack[i]();
        });
        _rmod.LOADED = true;
    }
};

_.rmod = namespaceToUri = function(script_name, url) {
    var np = script_name.split('.');
    if (np.getLast() === '*') {
        np.pop();
        np.push('_all');
    }

    if(!url)
        url = '';

    script_name = np.join('.');
    return  url + np.join('/')+'.js';
};

//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.
var require = function(script_name) {
    var uri = '';
    if (script_name.indexOf('/') > -1) {
        uri = script_name;
        var lastSlash = uri.lastIndexOf('/');
        script_name = uri.substring(lastSlash+1, uri.length);
    } else {
        uri = _rmod.namespaceToUri(script_name, ivar._private.libpath);
    }

    if (!_rmod.loading.scripts.hasOwnProperty(script_name) 
     && !_rmod.imported.hasOwnProperty(script_name)) {
        _rmod.injectScript(script_name, uri, 
            _rmod.requireCallback, 
                _rmod.requirePrepare);
    }
};

var ready = function(fn) {
    _rmod.on_ready_fn_stack.push(fn);
};
share|improve this answer

What's wrong with something like the following?

xhr = new XMLHttpRequest();
xhr.open("GET", "/soap/ajax/11.0/connection.js", false);
xhr.send();
eval(xhr.responseText);
share|improve this answer
var s=["Hscript.js","checkRobert.js","Hscript.js"];
for(i=0;i<s.length;i++){
  var script=document.createElement("script");
  script.type="text/javascript";
  script.src=s[i];
  document.getElementsByTagName("head")[0].appendChild(script)
};
share|improve this answer
This doesn't seem like a complete answer. – Lee Taylor Mar 10 at 14:11
     var s=['Hscript.js','checkRobert.js','Hscript.js'];
 for(i=0;i<s.length;i++){

   var script = document.createElement('script');

   script.type = 'text/javascript';

   script.src = s[i];


document.getElementsByTagName("head")[0].appendChild(script);

  }
share|improve this answer

Now, I may be totally misguided, but here's what I've recently started doing... Start and end your JavaScript files with a carriage return, place in the PHP script, followed by one more carriage return. The JavaScript comment "//" is ignored by PHP so the inclusion happens anyways. The purpose for the carriage returns, is so that the first line of your included JavaScript isn't commented out.

Technically you don't need the comment, but it posts errors in Dreamweaver that annoy me. If you're scripting in an IDE that doesn't post errors, you shouldn't need the comment or the carriage returns.

\n
//<?php require_once("path/to/javascript/dependency.js"); ?>

function myFunction(){
    // stuff
}
\n
share|improve this answer

Don't forget to check out LAB.js!

<script type="text/javascript">
       $LAB
       .script("jquery-1.8.3.js").wait()
       .script("scripts/clientscript.js");      
</script>
share|improve this answer

If anyone is looking for something more advanced, try out RequireJS.

You'll get added benefits such as dependency management, better concurrency, and avoid duplication (i.e. retrieving a script more than once).

You can write your JS files in "modules" and then reference them as dependencies in other scripts. Or you can use RequireJS as a simple "go get this script" solution.

Example:

Define dependencies as modules:

some-dependency.js

define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {

     //Your actual script goes here.   
     //The dependent scripts will be fetched if necessary.

     return libraryObject;  //e.g. jQuery object
});

implementation.js is your "main" javascript file that depends on some-dependency.js

require(['some-dependency'], function(dependency) {

    //Your script goes here
    //some-dependency.js is fetched.   
    //then your script is executed
});
share|improve this answer
1  
+1 for citing the right way to do it :-) It would be even better if you included an example! – Sean Vieira Jan 2 at 2:15
@Sean per your suggestion - I added a short example – John Strickler Jan 2 at 15:15
How is this not the accepted answer!? – aaaidan Mar 7 at 22:28

Better use JQuery way. To delay the ready event, first call $.holdReady(true). Example (source):

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});
share|improve this answer
var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);
share|improve this answer

There is a good news for you. Very soon you will be able to load javascript easily. It will become a standard way of importing modules of javascript and will be part of core javascript itself.

You simply have to write import cond from 'cond.js'; to load a macro named cond from a file cond.js

So you don't have to rely upon any javascript framework nor you have to explicitly make AJAX calls Refer to the links below

Source 1

Source 2

share|improve this answer
+1 That is neat! – Laurent Couvidou Jan 24 at 11:26
require/import on the jsfile has been way too long in the coming. (IMO). – rwheadon Apr 10 at 16:12

Or rather than including at run time, use a script to concatenate prior to upload.

I use Sprockets (I don't know if their are others). You build your JS in separate files and include comments that are processed by the Sprockets engine as includes. For Dev you can include files sequentially, then for production merge them...

http://37signals.com/svn/posts/1587-introducing-sprockets-javascript-dependency-management-and-concatenation

https://github.com/sstephenson/sprockets

share|improve this answer

This is perhaps the biggest weakness of Javascript in my opinion. Its caused me no end of problems over the years with dependency tracing. Anyhow it does appear that the only practical solution is to use script includes in the HTML file and thus horribly making your JS dependent upon the user including the source you need and making reuse unfriendly.

Sorry if this comes across as a lecture ;) Its a bad habit of mine, but I want to make a point.

The problem comes back to the same as everything else with the web, the history of Javascript. It really wasn't designed to be used in the widespread manner its used in today. Netscape made a language that would allow you to control a few things but didn't envisage its widespread use for so many things as it is put to now and for one reason or another its expanded from there, without addressing some of the fundamental weaknesses of he original strategy. Its not alone of course, HTML wasn't designed for the modern webpage, it was designed to be a way of expressing the logic of a document, so that readers (browsers in the modern world) could display this in an applicable form that was within the capabilities of the system and it took years for a solution (other than the hacks of MS and Netscape) to come along. CSS solves this problem but it was a long time coming and even longer to get people to use it rather than the established BAD techniques, it happened though, praise be.

Hopefully Javascript (especially now its part of the standard) will develop to take on board the concept of proper modularity (as well as some other things) as every other (extant) programming language in the world does and this stupidity will go away, until then you just have to not like it and lump it I'm afraid.

share|improve this answer
1  
"it's part of the standard" :D Good comments though. – Almo Jun 5 '12 at 14:45
ecmascript 6 seems like a real programming language. until then, we need to bear with it. – bighostkim Feb 23 at 18:24

I came to this question because I was looking for a simple way to maintain a collection of useful JavaScript plugins. After seeing some of the solutions here, I came up with this:

1) Set up a file called "plugins.js" (or extentions.js or what have you). Keep your plugin files together with that one master file.

2) plugins.js will have an array called "pluginNames[]" that we will iterate over each(), then append a tag to the head for each plugin

//set array to be updated when we add or remove plugin files
 var pluginNames = ["lettering", "fittext", "butterjam", etc.];
//one script tag for each plugin
 $.each(pluginNames, function(){
   $('head').append('<script src="js/plugins/' + this + '.js"></script>');
 });

3) manually call just the one file in your head:
<script src="js/plugins/plugins.js"></script>

UPDATE: I found that even though all of the plugins were getting dropped into the head tag the way they ought to, they weren't always being run by the browser when you click into the page or refresh.

I found it's more reliable to just write the script tags in a PHP include. You only have to write it once and that's just as much work as calling the plugin using JavaScript.

share|improve this answer
@will, your solution looks much cleaner than mine and I'm worried I might have some errors if I use mine, as it makes use of .append(). So to use this, you can just call that function once for each plugin file you wish to include? – rgb_life Dec 1 '11 at 5:55

In a past project I had quite a bit of success using ajile to do imports of reusable JavaScript files. I always wished there was a feature for this built into JavaScript itself.

share|improve this answer

I have created a function that will allow you to use similar verbiage to C#/Java to include a Javascript file. I've tested it a little bit even from inside of another Javascript file and it seems to work. It does require jQuery though for a bit of "magic" at the end. I put this code in a file at the root of my script directory (I named it global.js but you can use whatever you want. Unless I'm mistaken this and jQuery should be the only required scripts on a given page. Keep in mind this is largely untested beyond some basic usage, so there may or may not be any issues with the way I've done it; use at your own risk yadda yadda I am not responsible if you screw anything up yadda yadda:

/**
* @fileoverview This file stores global functions that are required by other libraries.
*/

if (typeof(jQuery) === 'undefined') {
    throw 'jQuery is required.';
}

/** Defines the base script directory that all .js files are assumed to be organized under. */
var BASE_DIR = 'js/';

/**
* Loads the specified file, outputting it to the <head> HTMLElement.
*
* This method mimics the use of using in C# or import in Java, allowing
* JavaScript files to "load" other JavaScript files that they depend on
* using a familiar syntax.
*
* This method assumes all scripts are under a directory at the root and will
* append the .js file extension automatically.
*
* @param {string} file A file path to load using C#/Java "dot" syntax.
* 
* Example Usage:
* imports('core.utils.extensions'); 
* This will output: <script type="text/javascript" src="/js/core/utils/extensions.js"></script>
*/
function imports(file) {
    var fileName = file.substr(file.lastIndexOf('.') + 1, file.length);

    // convert PascalCase name to underscore_separated_name
    var regex = new RegExp(/([A-Z])/g);
    if (regex.test(fileName)) {
        var separated = fileName.replace(regex, ",$1").replace(',', '');
        fileName = separated.replace(/[,]/g, '_');
    }

    // remove the original js file name to replace with underscore version
    file = file.substr(0, file.lastIndexOf('.'));

    // convert the dot syntax to directory syntax to actually load the file
    if (file.indexOf('.') > 0) {
        file = file.replace(/[.]/g, '/');
    }

    var src = BASE_DIR + file + '/' + fileName.toLowerCase() + '.js';
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;

    $('head').find('script:last').append(script);
}
share|improve this answer

Oh gosh~!! I have this issue for few days and I tried many methods that drive me crazy. I having 7 complected js file to include on the fly and it not perfectly working. when I try to refresh it each time i will hit some error, the chances to hit error are 1/20. until i found this lovely function

  ------------------------------------
  function includeJS(jsPath){
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", jsPath);
    document.getElementsByTagName("head")[0].appendChild(script);
  }
  ------------------------------------

the key that fix my problem is "create the DOM object in html's HEAD". not in body, do not use document.write(), jquery.append()... they are work but not perfect!!!!

share|improve this answer
2  
This answer shows little research effort, and is very poor-quality. – IDWMaster Jan 2 '12 at 21:38

Another way, that in my opinion is much cleaner, is to make a synchronous ajax request instead of using a <script> tag. Which is also how node.js handles includes.

Here's an example using jQuery:

function require(script) {
    $.ajax({
        url: script,
        dataType: "script",
        async: false,           // <-- this is the key
        success: function () {
            // all good...
        },
        error: function () {
            throw new Error("Could not load script " + script);
        }
    });
}

You can then use it in your code as you'd usually use an include:

require("/scripts/subscript.js");

And be able to call a function from the required script in the next line:

subscript.doSomethingCool(); 
share|improve this answer
Good solution, the head include is async unfortunately, the ajax solution works. – contam Nov 25 '11 at 9:21
6  
As someone else mentioned, requirejs.org does this and also has a pre-compiler that puts js files together so they load faster. You may want to check it out. – Ariel Jan 9 '12 at 6:57
Good solution. Seems to work. Keep in mind, the path you pass to require will be relative to the page your loading the scripts on, and not the scripts themselves. – BrainSlugs83 Jul 21 '12 at 10:00
1  
Correct. That's why I prefer absolute urls ;) – Ariel Jul 24 '12 at 0:02
1  
Found I could do debug it by adding this directive at the bottom of the file for Chrome : //@ sourceURL=view_index.js – toddv Apr 11 at 0:02
show 2 more comments

In response to e-satis comment:

there actually is a way to load a javascript file not asynchronously, so you could use the functions included in your newly loaded file right after loading it, and i think it works in all browsers. You need to use jQuery.append() on the <head> element of your page, i.e. :

$("head").append('<script type="text/javascript" src="' + script + '"></script>');

However, this method also has a problem: if an error happens in the imported js file, Firebug (and also Firefox Error Console and Chrome Developer Tools as well) will report it's place incorrectly, which is a big problem if you use Firebug to track js errors down alot (i do). Firebug simply doesn't know about the newly loaded file for some reason, so if an error occurs in that file, it reports that it occurred in your main html file and you will have trouble finding out the real reason for the error.

But if that is not a problem for you, then this method should work.

I have actually written a jQuery plugin called $.import_js() which uses this method:

(function($)
{
    /*
     * $.import_js() helper (for javascript importing within javascript).
     */
    var import_js_imported = [];

    $.extend(true,
    {
        import_js : function(script)
        {
            var found = false;
            for (var i = 0; i < import_js_imported.length; i++)
                if (import_js_imported[i] == script) {
                    found = true;
                    break;
                }

            if (found == false) {
                $("head").append('<script type="text/javascript" src="' + script + '"></script>');
                import_js_imported.push(script);
            }
        }
    });

})(jQuery);

So all you would need to do to import js is:

$.import_js('/path_to_project/scripts/somefunctions.js');

I also made a simple test for this at : http://www.kipras.com/dev/import_js_test/

What it does is it includes a main.js file in the main HTML and then the script in main.js uses $.import_js() to import an additional file called included.js, which defines this function:

function hello()
{
    alert("Hello world!");
}

And right after including included.js, the hello() function is called, and you get the alert.

share|improve this answer
I am trying this method, but is not working for me, the element just does not appear in head tag. – juanpastas Mar 12 at 15:24

You can also assemble your scripts using php:

main.js.php:

<?php

header('Content-type:text/javascript; charset=utf-8');
include_once("foo.js.php");
include_once("bar.js.php");

?>

// main javascript goes here
share|improve this answer
4  
Sounds like the point is to keep this all in javascript in the front end – Ariel Sep 8 '11 at 18:23

Maybe you can use this function that I found on this page: http://forums.digitalpoint.com/showthread.php?t=146094

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';

    head.appendChild(script)
}
share|improve this answer
3  
To be accurate: script variable should be declared with var in order not to spawn globals. – Svitlana Maksymchuk Jun 4 '09 at 12:21

I just wrote this JS (using prototype.js for DOM manipulation):

var require = (function () {
var _required = {};
return (function (url, callback) {
    if (typeof url == 'object') {
        // we've (hopefully) got an array: time to chain!
        if (url.length > 1) {
            // load the nth file as soon as everything up to the
            // n-1th one is done.
            require(url.slice(0,url.length-1), function () {
                require(url[url.length-1], callback);
            });
        } else if (url.length == 1) {
            require(url[0], callback);
        }
        return;
    }
    if (typeof _required[url] == 'undefined') {
        // haven't loaded this url yet; gogogo!
        _required[url] = [];

        var script = new Element('script', {src:url, type:'text/javascript'});
        script.observe('load', function () {
            console.log("script " + url + " loaded.");
            _required[url].each(function (cb) {
                cb.call(); // TODO does this execute in the right context?
            });
            _required[url] = true;
        });

        $$('head')[0].insert(script);
    } else if (typeof _required[url] == 'boolean') {
        // we already loaded the thing, so go ahead
        if (callback) { callback.call(); }
        return;
    }

    if (callback) { _required[url].push(callback); }
});
})();

Usage:

<script src="prototype.js"></script>
<script src="require.js"></script>
<script>
    require(['foo.js','bar.js'], function () {
        /* use foo.js and bar.js here */
    });
</script>

Gist: http://gist.github.com/284442

share|improve this answer
2  
jrburke wrote this as RequireJS. Github: requirejs.org/docs/requirements.html – Mike Caron Sep 14 '11 at 17:14

It is possible dynamically generate javascript tag and append it to HTML doc from inside another javascript. This will load targeted js file.

function includeJs(jsFilePath) {
    var js = document.createElement("script");

    js.type = "text/javascript";
    js.src = jsFilePath;

    document.body.appendChild(js);
}

includeJs("/path/to/some/file.js");
share|improve this answer
It does work, but has serious issues because of the asynchonous loading. – e-satis Jun 4 '09 at 12:11
Um... which exactly? – Svitlana Maksymchuk Jun 4 '09 at 12:14
1  
@e-satis - Actually, this is an advantage, a sync script would be blocking. Horses for courses, but 9 times in 10 you want the non-blocking option. – annakata Jun 4 '09 at 12:15
@Svitlana - script elements created like this are async. Currently this could be viewed as exploiting a loophole so it might not be future proof, I've not seen anything in any standard which clarifies this. – annakata Jun 4 '09 at 12:16
Actually I take it back, I've noticed you're appending to body rather than head. – annakata Jun 4 '09 at 12:19
show 3 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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