Is there something similar to @import
in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?
|
|||||||||||||
|
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:
|
|||||||||||||||||
|
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:
|
|||||||||||||||||||||
|
You can also assemble your scripts using PHP: File
|
|||||||||
|
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.
|
|||||||||
|
|
|||||
|
Don't forget to check out LAB.js!
|
|||||
|
|
||||
|
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. |
||||
|
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. |
|||
|
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?