Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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
23  
12  
@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

39 Answers 39

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.

...

share|improve this answer
6  
+1 for citing the right way to do it :-) It would be even better if you included an example! – Sean Vieira Jan 2 '13 at 2:15
6  
@Sean per your suggestion - I added a short example – John Strickler Jan 2 '13 at 15:15
25  
@aaaidan - perhaps because it was added 3 years after the question was asked... – MattDMo Jun 1 '13 at 17:46
1  
@aaaidan: MattDmo's reason plus it relies on an external library which in return rely on the accepted answer. – David Mulder Mar 20 '14 at 21:28

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
1  
Good solution, the head include is async unfortunately, the ajax solution works. – Matteo Conta Nov 25 '11 at 9:21
12  
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
2  
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 '13 at 0:02
7  
unfortunatelly, async:false is now deprecated in jQuery. Might break in the future, so i'd avoid. – sqram Oct 17 '13 at 1:45
2  
@katsh We are not using jqXHR objects here. Your quote doesn't seem to back up your previous comment stating that async: false supposedly is deprecated. It is not! As your quote states, only the jqXHR related stuff is. – Zero3 Apr 27 at 16:50

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
share|improve this answer
13  
Sounds like the point is to keep this all in javascript in the front end – Ariel Sep 8 '11 at 18:23
1  
Thanks for reminding this. You can also have PHP write <script> tags in your HTML header, so that the js files you need (and only those) will be loaded. – Rolf Dec 18 '13 at 12:38

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");
share|improve this answer
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
1  
@e-satis asynchronous is good because it wont freeze your page. Use callback to be notified when it's done js.onload = callback; – Vitim.us Aug 23 '13 at 15:40
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
1  
This doesn't seem like a complete answer. – Lee Taylor Mar 10 '13 at 14:11

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
1  
Unfortunately, it's not really under development any more, and there's no guarantee that some future browser or JS engine or language version won't break it. You should try to be as up-to-date as possible with JS, although there is something to be said for stability. Even though this could be a good option for somebody, I'd much rather steer them toward RequireJS or jQuery.getScript(), both of which are stable and under constant development. – MattDMo Jun 1 '13 at 18:02
var js = document.createElement("script");

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

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

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

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

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

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, 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.