Is there something similar to @import
in CSS in JavaScript that allows you to include a JavaScript file inside a JavaScript file?
|
|||||||||||||||||||||
|
There is no import / include / require in javascript, but there are two main ways to achieve what you want: 1 - You can load it with an AJAX call then use eval. This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks. 2 - Add a script tag with the script URL in the HTML. 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 here. 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 performances. 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. E.G : my_lovely_script.js contains MySuperObject
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. E.G :
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 framework, which let you do the very same thing in one line :
|
|||||||||||||||||||||
|
I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/
|
||||
|
What's wrong with something like the following?
|
||||
|
|
||||
|
|
|||
|
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 anyways. 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.
|
|||
|
Don't forget to check out LAB.js!
|
|||
|
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 (i.e. retrieving a script more than once). You can write your JS 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
|
|||||||||
|
Better use JQuery way. To delay the ready event, first call $.holdReady(true). Example (source):
|
|||
|
|
||||
|
There is a good news for you. Very soon you will be able to load javascript easily. It will become a standard way of importing modules of javascript 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 you have to explicitly make AJAX calls Refer to the links below |
|||||
|
Or rather than including at run time, use a script to concatenate prior to upload. I use Sprockets (I don't know if their are others). You build your JS in separate files and include comments that are processed by the Sprockets engine as includes. For Dev you can include files sequentially, then for production merge them... |
|||
|
This is perhaps the biggest weakness of Javascript in my opinion. Its 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 JS dependent upon the user including the source you need and making reuse unfriendly. Sorry if this comes across as a lecture ;) Its 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 its used in today. Netscape made a language that would allow you to control a few things but didn't envisage its widespread use for so many things as it is put to now and for one reason or another its expanded from there, without addressing some of the fundamental weaknesses of he original strategy. Its 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 its 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 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. |
|||
|
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
|
|||
|
Oh gosh~!! I have this issue for few days and I tried many methods that drive me crazy. I having 7 complected js file to include on the fly and it not perfectly working. when I try to refresh it each time i will hit some error, the chances to hit error are 1/20. until i found this lovely function
the key that fix my problem is "create the DOM object in html's HEAD". not in body, do not use document.write(), jquery.append()... they are work but not perfect!!!! |
|||||
|
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:
|
|||||||||||||||||
|
In response to e-satis comment: 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 jQuery.append() on the
However, this method also has a problem: if an error happens in the imported js file, Firebug (and also Firefox Error Console and Chrome Developer Tools as well) will report it's place incorrectly, which is a big problem if you use Firebug to track js errors down alot (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 js is:
I also made a simple test for this at : http://www.kipras.com/dev/import_js_test/ What it does is it includes a
And right after including included.js, the hello() function is called, and you get the alert. |
||||
|
You can also assemble your scripts using php: main.js.php:
|
|||||
|
Maybe you can use this function that I found on this page: http://forums.digitalpoint.com/showthread.php?t=146094
|
|||||
|
I just wrote this JS (using prototype.js for DOM manipulation):
Usage:
|
|||||
|
It is possible dynamically generate javascript tag and append it to HTML doc from inside another javascript. This will load targeted js file.
|
|||||||||||||
|