How to include a JavaScript file in another JavaScript file?
11
Is there something similar to @import in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?
improve this question | comment
Krystina Shields Created at: 2013-11-13 17:07:17 UTC By Krystina Shields
stackoverflow.com/questions/21294/… - Evalyn Parker
@Daniel, I do not want to use an AJAX call. - Vidal Berge
Nonetheless the answers are the same. - Tobin Russel
Take a look at the other questions. - Camren Bednar
29 Answers
0
function include(js)
{
    document.writeln("<script src=" + js + "><" + "/script>");
}

0
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);
}

0
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, that is:

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


However, this method also has a problem: if an error happens in the imported JavaScript file, Firebug (and also Firefox Error Console and Chrome Developer Tools as well) will report its place incorrectly, which is a big problem if you use Firebug to track JavaScript errors down a lot (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 code).
     */
    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 JavaScript 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/.

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.

(This answer is in response to e-satis' comment.)
0
This script will add JavaScript file to the top of any other <script> tag:

(function () {
    var li = document.createElement('script'); 
    li.type = 'text/javascript'; 
    li.src= "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"; 
    li.async=true; 
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(li, s);
})();

0
I also wrote a JavaScript dependency manager for Java web apps: JS-Class-Loader.
0
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(); 

0
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
0
Maybe you can use this function that I found page How do I include a JavaScript file in a JavaScript file?:

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

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

    head.appendChild(script)
}

0
It is possible to dynamically generate a JavaScript tag and append it to HTML document from inside other JavaScript code. This will load targeted JavaScript 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");

0
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
0
You can also assemble your scripts using PHP:

File main.js.php:

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

// Main JavaScript code goes here

0
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. 
0
Most of solutions shown here imply dynamical loading. I was searching instead for a compiler which assemble all the depended files into a single output file. The same as less/sass preprocessors deal with CSS @import at-rule. Since I didn't find anything decent of this sort, I wrote a simple tool solving the issue. 
So here is the compiler https://github.com/dsheiko/jsic which replace $import("file-path") with the requested file content securely. Here is the corresponding GRUNT plugin https://github.com/dsheiko/grunt-jsic

On jQuery master branch they simply concatenate atomic source files into a single one starting with intro.js and ending with outtro.js. That doesn't suite me as it provides no flexibility on the source code design. Check out how it works with jsic:

src/main.js   

var foo = $import("./Form/Input/Tel");


src/Form/Input/Tel.js

function() {
    return {
          prop: "",
          method: function(){}
    }
}


Now we can run the compiler:

node jsic.js src/main.js build/mail.js


And get the combined file

build/main.js

var foo = function() {
    return {
          prop: "",
          method: function(){}
    }
};

0
I just wrote this JavaScript code (using Prototype 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
0
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 (that is, retrieving a script more than once).

You can write your JavaScript 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;  //For example, 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
});


Excerpt from the GitHub README:


  RequireJS loads plain JavaScript files as well as more defined
  modules. It is optimized for in-browser use, including in a Web
  Worker, but it can be used in other JavaScript environments, like
  Rhino and Node. It implements the Asynchronous Module API.
  
  RequireJS uses plain script tags to load modules/files, so it should
  allow for easy debugging. It can be used simply to load existing
  JavaScript files, so you can add it to your existing project without
  having to re-write your JavaScript files.
  
  ... 

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

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

document.body.appendChild(js);

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

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});

0
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)
};

0
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);

0
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.
0
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.
0
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>

0
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

0
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);
};

0
I did:

var require = function (src, cb) {
    cb = cb || function () {};

    var newScriptTag = document.createElement('script'),
        firstScriptTag = document.getElementsByTagName('script')[0];
    newScriptTag.src = src;
    newScriptTag.async = true;
    console.log(newScriptTag)
    newScriptTag.onload = newScriptTag.onreadystatechange = function () {
        (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') && (cb());
    };
    firstScriptTag.parentNode.insertBefore(newScriptTag, firstScriptTag);
}


Works great and uses no page-reloads for me. Tried that AJAX thing. It doesn't really work.
0
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);
}

0
Here is a Grunt plugin allowing you to use @import "path/to/file.js"; syntax in any file including JavaSript files. It can be paired with uglify or watch or any other plugin.

Can be installed with npm install: https://npmjs.org/package/grunt-import

Let me know if any questions.
0
If you want in pure JavaScript, you can use document.write.

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


If you use the jQuery library, you can use the $.getScript method.

$.getScript("another_script.js");

0
There isn't any import, include or require in JavaScript, but there are two main ways to achieve what you want:

1 - You can load it with an Ajax call and 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.

This is 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 in JavaScript Madness: Dynamic Script Loading.

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 performance.

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.

For example: 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. For example:

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
});

Your Answer