Is there something similar to @import
in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?
|
|||||||||||||
|
JavaScript has no import, include, or require. (Update 2015: it does now with ES6 modules) There are other ways for JavaScript to include external JavaScript contents, though. Ajax LoadingLoad an additional script with an Ajax call and then use jQuery LoadingThe jQuery library provides loading functionality in one line:
Dynamic Script LoadingAdd a script tag with the script URL in the HTML. To avoid the overhead of jQuery, this is an ideal solution. The script can even reside on a different server. Furthermore, the browser evaluates the code. The Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading. Detecting when the script has been executedNow, 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. (This applies to both the jQuery method and the manual dynamic script loading method.) 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:
Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line Source Code MergeAnother solution is to combine the two files into a single file. This can be used with minification to produce a single, minimally sized JavaScript file to include as normal. |
|||||||||||||||||||||
|
Here is the JavaScript Snippet from Google Advanced Configuration to asynchronously loads their analytics.js library onto the page.
This code is work perfectly to load another-javascript-file to the page, so far I have never found a snippet with such of configuration similar to it. |
|||||
|
If your intention to load js file is that using the functions from the imported/included file, you can also define a global object and set the functions as object item. For instance: global.js
file1.js
file2.js
main.js
You just need to be careful when you are including scripts in html file, the order should be as in below:
|
|||
|
I had a simple issue, but baffled by responses to this question. I had to use a variable (myVar1) defined in one JS file (myvariables.js) in another JS file (main.js). For this I did as below:
File: mystruct.js
File: main.js
As you saw, I had use variable in one JS file in another JS file This saved my day. Hope this helps someone else. (Up-vote & Mark this as answer if it serves your need too.) |
||||
|
Here's the generalized version of how Facebook does it for their ubiquitous Like button:
If it works for Facebook, it will work for you. The reason why we look for the first |
||||
|
Here is a synchronous version without jQuery:
Note that to get this working cross-domain, the server will need to set |
|||||
|
I just wrote this JavaScript code (using Prototype for DOM manipulation):
Usage:
|
|||||
|
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). |
|||||
|
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 UPDATE: Mixture is now free. |
||||
|
Syntax
|
|||||
|
Keep it nice, short, simple, and maintainable! :]
This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform. |
|||
|
There are a lot of potential answers for this questions. My answer is obviously based on a number of them. Thank you for all the help. This is what I ended up with after reading through all the answers. The problem with $.getScript and really any other solution that requires a callback when loading is complete is that if you have multiple files that use it and depend on each other you no longer have a way to know when all scripts have been loaded. (Once they are nested in multiple files.) ex: file3.js
file2.js:
file1.js:
You are right when you say that you could specify ajax to run synchronously or use XMLHttpRequest, but the current trend appears to be to deprecate synchronous requests, so you may not get full browser support now or in the future. You could try to use $.when to check an array of deferred objects, but now you are doing this in every file and file2 will be considered loaded as soon as the $.when is executed not when the callback is executed so file1 still continues execution before file3 is loaded. This really still has the same problem. I decided to go backwards instead of forwards. Thank you document.writeln. I know its taboo, but as long as it is used correctly this works well. You end up with code that can be debugged easily, shows in the DOM correctly and can ensure the order the dependencies are loaded correctly. You can of course use $("body").append(), but then you can no longer debug correctly anymore. NOTE: you must use this only while the page is loading, otherwise you get a blank screen. In other words, always place this before / outside of document.ready. I have not tested using this after the page is loaded in a click event or anything like that, but pretty sure it'll fail. I liked the idea of extending JQuery, but obviously you don't need to. Before calling document.writeln, it checks to make sure the script has not already been loading by evaluating all the script elements. I assume that a script is not fully executed until its document.ready event has been executed. (I know using document.ready is not required, but many people use it, handling this is a safeguard.) When the additional files are loaded the document.ready callbacks will get executed in the wrong order. To address this when a script is actually loaded, the script that imported it is re-imported itself and execution halted. This causes the originating file to now have it's document.ready callback executed after any from any scripts that it imports. Instead of this approach you could attempt to modify the JQuery readyList but this seemed like a worse solution. solution:
usage: file3:
file2:
file1:
|
|||
|
In case you are using Web Workers and want to include additional scripts in the scope of the worker, the other answers provided about adding scripts to the Fortunately, Web Workers have their own Alternatively, as the second highest voted answer to your question highlights, RequireJS can also handle including scripts inside a Web Worker (likely calling |
||||
|
Maybe you can use this function that I found on this page How do I include a JavaScript file in a JavaScript file?:
|
|||||
|
This should do:
|
|||||||||||||||||||||
|
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.
|
||||
|
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 |
||||
|
Here is a Grunt plugin allowing you to use It can be installed with npm install: https://npmjs.org/package/grunt-import |
||||
|
I also wrote a JavaScript dependency manager for Java web applications: JS-Class-Loader. |
||||
|
This script will add a JavaScript file to the top of any other
|
||||
|
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
|
|||||
|
I did:
It works great and uses no page-reloads for me. I tried that Ajax thing, but it doesn't really work. |
||||
|
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.
|
||||
|
Better use the jQuery way. To delay the ready event, first call
|
||||
|
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: |
|||||||||||||
|
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: |
||||
|
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. |
|||||||||
|
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
|
||||
|
If you want in pure JavaScript, you can use document.write.
If you use the jQuery library, you can use the $.getScript method.
|
|||||||||
|
|
|||||
|
protected by NullPoiиteя 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?