31

How do you load one JavaScript file from another JavaScript file, like CSS? In CSS we use write @import url("mycss.css");.

Is there any way to do it in JavaScript?

1

5 Answers 5

53

There's no @import-ish function/method in Javascript, but you can simply append a script to the <head> tag like so:

var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/path/to/js/file';
document.getElementsByTagName('head')[0].appendChild(newScript);

Or like Edgar mentioned right before me you can use jQuery.

Sign up to request clarification or add additional context in comments.

5 Comments

Does this load the file and initiate all the contents written on it?
because I'm looking forward to writing this code to load jQuery
@RajaAnbazhagan yes it will initiate the contents of the file, I've actually used it to load jQuery so I know that works.
Why not use document.head.appendChild instead
This was posted in the dark ages of browsers where IE8 and its ilk before didn't support document.head.
33

Yes. If you want in pure JavaScript, you have to create dynamically a script tag, and append it to the document.

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

$.getScript("another_script.js");

1 Comment

Note: If you're getting "getScript is not defined", you probably loaded the wrong version of jQuery. See [stackoverflow.com/questions/35424053/… are the differences between normal and slim package of jquery?)
19

Just because no-one has mentioned it yet, there's another option, which doesn't require any fancy libraries or tricky coding, document.write. In principal, it would look like this, although see below for a caveat:

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

This will be executed upon completely parsing the script tag, and if you put your script tag in the head, the new script tag will also be in the head, right after the one being executed. Take care to execute it directly rather than when the document has been loaded (as in a $(function(){}) callback. This is what I use:

(function(){
  function load(script) {
    document.write('<'+'script src="'+script+'" type="text/javascript"><' + '/script>');
  }

  load("script1.js");
  load("script2.js");
  load("etc.js");
})();

The enclosing function is just there to not pollute the global namespace.

The caveat (and why the 'script' that is broken up above) is that there may be no ending script tags within a script tag, the HTML parser doesn't know it's part of the script. There's an other question on that subject.

Comments

6

Javascript itself doesn't provide any help with modularization other than the ability to eval a string. But this is a common-enough need that most big javascript frameworks have come up with their own solutions, and more recently, there has been an effort to standardize those APIs in the requirejs project. If you're using a framework like Dojo or jQuery, you're probably just best off learning to use their facilities, but if not, requirejs is a lightweight standalone tool. You basically just add

<script data-main="scripts/main" src="scripts/require.js"></script>

to your <head> section, and then put your own javascript inside some wrapper code like this (stolen from the require.js site):

require(["helper/util"], function() {
    //This function is called when scripts/helper/util.js is loaded.

    require.ready(function() {
        //This function is called when the page is loaded
        //(the DOMContentLoaded event) and when all required
        //scripts are loaded.

    });
});

Comments

-1

use const dataName =require('./fileName.js');

1 Comment

This both lacks context and does not work. I tried a creating a mock-up to see if it would function as intended, and it did not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.