Is there something similar to @import
in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?
|
|||||||||||||
|
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 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 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:
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:
Then you write the code you want to use AFTER the script is loaded in a lambda function:
Then you run all that:
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 library, which let you do the very same thing in one line:
|
|||||||||||||||||||||
|
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
implementation.js is your "main" JavaScript file that depends on some-dependency.js
Excerpt from the GitHub README:
|
|||||||||||||||||
|
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
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:
So all you would need to do to import JavaScript is:
I also made a simple test for this at http://www.kipras.com/dev/import_js_test/. It includes a
And right after including (This answer is in response to e-satis' comment.) |
|||||
|
Another way, that in my opinion is much cleaner, is to make a synchronous Ajax request instead of using a Here's an example using jQuery:
You can then use it in your code as you'd usually use an include:
And be able to call a function from the required script in the next line:
|
|||||||||||||||||||||
|
There is a good news for you. Very soon you will be able to load JavaScript code easily. It will become a standard way of importing modules of JavaScript code and will be part of core JavaScript itself. You simply have to write So you don't have to rely upon any JavaScript framework nor do you have to explicitly make Ajax calls. Refer to: |
|||||||||||||
|
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.
|
|||||
|
Maybe you can use this function that I found page How do I include a JavaScript file in a JavaScript file?:
|
|||||
|
You can also assemble your scripts using PHP: File
|
|||||||||
|
I just wrote this JavaScript code (using Prototype for DOM manipulation):
Usage:
|
|||||
|
Or rather than including at run time, use a script to concatenate prior to upload. I use Sprockets (I don't know if there are others). You build your JavaScript code in separate files and include comments that are processed by the Sprockets engine as includes. For development you can include files sequentially, then for production to merge them... See also: |
||||
|
Here is a synchronous version without jQuery:
|
||||
|
This is perhaps the biggest weakness of JavaScript in my opinion. It's 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 JavaScript code dependent upon the user including the source you need and making reuse unfriendly. Sorry if this comes across as a lecture ;) It's 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 it's used in today. Netscape made a language that would allow you to control a few things, but they didn't envisage its widespread use for so many things as it is put to now and for one reason or another it's expanded from there, without addressing some of the fundamental weaknesses of he original strategy. It's 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 it's 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. |
|||||
|
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 the CSS So here is the compiler, https://github.com/dsheiko/jsic, which replaces On the jQuery master branch, they simply concatenate atomic source files into a single one starting with src/main.js
src/Form/Input/Tel.js
Now we can run the compiler:
And get the combined file build/main.js
|
|||||
|
What's wrong with something like the following?
|
|||||||||
|
|
||||
|
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
3) manually call just the one file in your head: 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. |
||||
|
|
||||
|
If you want in pure JavaScript, you can use document.write.
If you use the jQuery library, you can use the $.getScript method.
|
|||||
|
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
|
||||
|
There is also Head.js. It is very easy to deal with:
As you see, it's easier than Require.js and as convenient as jQuery's |
||||
|
|
||||
|
Better use the jQuery way. To delay the ready event, first call
|
||||
|
The From the Mixture documentation on
Here's an example
Mixture outputs this as Note: I'm not in any way affiliated with Mixture, other than using it as a front-end development tool. I came across this question upon seeing a |
||||
|
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. |
||||
|
Don't forget to check out LAB.js!
|
|||||
|
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 anyway. 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.
|
||||
|
I did:
It works great and uses no page-reloads for me. I tried that Ajax thing, but it doesn't really work. |
||||
|
Here is a Grunt plugin allowing you to use It can be installed with npm install: https://npmjs.org/package/grunt-import |
||||
|
I wrote a simple module that automates the job of importing/including module scripts in JavaScript. For detailed explanation of the code, refer to the blog post JavaScript require / import / include modules.
|
||||
|
|
|||||
|
protected by obi NullPoiиteя kenobi 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?