I was wondering if there was a way to include a js file in another js file so that you can reference it. What I'm asking for is the JS equivalent of include() in PHP.
I've seen a lot of people recommend this method as an example:
document.write('<script type="text/javascript" src="globals.js"></script>');
But I'm not sure if that's the same as include()
Check out http://requirejs.org/ . You can define (AMD) modules and reference them in other modules like so
define(["path/to/module1", "path/to/module1")], function(Module1, Module2) {
//you now have access
});
Don't use document.write, it could wipeout the entire page if the page has already written. You can write something simple like this:
var jsToInclude = document.createElement('script');
jsToInclude.type = 'type/javascript';
jsToInclude.src = '/dir/somefile.js'; // path to the js file you want to include
var insertionPointElement = document.getElementsByTagName('script')[0]; // it could be the first javascript tag or whatever element
insertionPointElement.parentNode.insertBefore(jsToInclude, insertionPointElement);
Related
I have 4 javascript files (each for a single HTML file) and 3 functions are THE SAME in all 4 files.
I'd like to find a smooth solution that I could somehow include these 3 functions separately... is it possible to include .js within a .js?
You can have multiple <script> tags:
<script src="lib.js"></script>
<script>
// do stuff
</script>
You can use jQuery:
$.getScript("lib.js", function() {
// do stuff
});
You can use a pre-processor like browserify or YUICompressor or Google's Closure Compiler.
You can write this by your own, for example as it works in google analytics:
(function(){
var lastIncludedScript = document.getElementsByTagName('script')[0];
var yourScript = document.createElement('script');
yourScript.type = 'text/javascript';
yourScript.src = 'path/to/script.js';
lastIncludedScript.parentNode.insertBefore(yourScript, lastIncludedScript);
})();
or as in function:
function includeScript( path ){
var lastIncludedScript = document.getElementsByTagName('script')[0];
var yourScript = document.createElement('script');
yourScript.type = 'text/javascript';
yourScript.src = path;
lastIncludedScript.parentNode.insertBefore(yourScript, lastIncludedScript);
}
usage:
includeScript( 'path/to/script.js' );
You can have a look at this nice explanation about loading javascript files asynchronously. This could solve your problem. Or look at this stack overflow question on how to load javascript files inside other javascript files.
However it may be worth a shot to include everything you use in one single javascript file and load the same one on every site. This improves performance because only one http request has to be made to load all javascript and it can be cached very efficiently (so no need to load any javascript later on).
Use proper js file required in each html file. That will solve your issue. Also the one contating the general functions can be added for both html files. This should solve your problem.
It's a bit slow to include files from other JavaScript in the browser. I would write a server-side script to combine and minify all relevant JavaScript into one "file" to be sent to the client.
Your pages can pass parameters to this script to choose what needs to be included.
is it possible to do something like this
to send the value id=3 to the js file
<script src="http://site.com/js/loader.js?id=3" ....
otherwise what's the approach to do that?
No, that won't work.
Just set the variables before you load the file:
<script>var id = 3;</script>
<script src="http://site.com/js/loader.js" ....
Since all the scripts share a global namespace, you'll be able to access the id variable from inside your loader.js file.
Of course you should think about the style and implications of using global vars to achieve that. Using a global object that hold these config variables might be a cleaner approach.
If that is just a javascript file, you can just define the variable before load it.
<script>
var id = 3;
</script>
<script src="http://site.com/js/loader.js" ....
It would work, but not if your .js URL is just for a static file. If you wrote server-side code that output JavaScript, then you could output custom JavaScript based on the query string.
This is probably overkill for what you're trying to achieve.
k so this question has pretty much been answered. But there is another approach, which may or may not be suitable for you. If you want to render script conditionally or fetch a certain script for a certain id. You can declare it in a serverside script
http://site.com/js/loader.js.php?id=1
In the loader.js.php
Just use the following line in the beginning
<?
header("Content-type: text/javascript");//To declare it is a javascript file
$id=$_REQUEST['id'];
?>
//Normal js continues after this
//When you need to use the variable, just use
var id=<?=$id?>
This is a demo files of the script I wish to place in these files in order to use the build script that comes with the HTML5 boiler plate. http://epecho.com/tst/index.html
those files have been "minified";
<!-- scripts concatenated and minified via ant build script-->
<!--<script src="js/plugins.js"></script>
<script src="js/script.js"></script>-->
However, if you want to modify them, you can just ad your own javascript to the file. Just make sure you do not overwrite them every time you update the scripts.
// your code goes here..
function foo() {
}
window.log = function(){
log.history = log.history || [];
log.history.push(arguments);
arguments.callee = arguments.callee.caller;
if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});
It is probably not good practice to do this, would be best to just make a new javascript file, and place your code in that file, and include it.
Create a file called whatever you like, "my code.js" is used in my example, and then include that as below in the html page.
<script src="js/mycode.js"></script>
I am making use of constructors (classes) extensively and would like each constructor to be in a separate file (something like Java). Suppose I have constructors say Class1, Class2, ... Class10 and I only want to use Class1 and Class5 I need to use script tags to include Class1.js and Class2.js into the HTML page. Later if I also need to use Class3 and Class6 I again need to go to the HTML page and add script tags for them. Maintenance with this approach is too poor.
Is there something in JavaScript similar to include directive of C? If not, is there a way to emulate this behavior?
You can use jQuery.getScript:
http://api.jquery.com/jQuery.getScript
Or any of the many javascript loaders like YUI, JSLoader, etc. See comparison here:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
You can use something like this:
jsimport = function(url) {
var _head = document.getElementsByTagName("head")[0];
var _script = document.createElement('script');
_script.type = 'text/javascript';
_script.src = url;
_head.appendChild(_script);
}
then use it in your code like:
jsimport("example.class.js");
Be careful to use this when the head is already in the DOM, else it won't work.
Yes: You can create script tags from JavaScript and load required classes on demand.
See here for a couple of solutions: http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
With careful use of id attributes or a global variable that contains "already loaded" scripts, it should be possible to develop a dependency resolution framework for JavaScript like Maven or OSGi for Java.
When we are talking about JavaScript, I feel it is better to include one file that includes everything you need instead of requesting a new file every time you need something that you don't currently have access to.
Each time you send out for another file, the browser will do many things. It checks if the requested file can in fact be found by sending an HTTPRequest, and if the browser has already seen this, is it cached and unchanged?
What you are wanting to do is not in the spirit of JavaScript. Doing what you are explaining will produce addition load times, and you wouldn't be able to do anything until the file has completely loaded, which creates wait times.
It would be better to use one file for this, include at the inner end of the </body tag (which won't cause the browser to wait until the script is done to load the page), then create one simple function that will execute when the page is completely loaded.
For example:
<html>
<head></head>
<body>
<!-- HTML code here... -->
<script src="javascript.js"></script>
<script>
(function r(f) {
/in/.test(document.readyState) ? setTimeout('r(' + f + ')', 9) : f()
})(function() {
// When the page has completey loaded
alert("DOM has loaded and is ready!");
});
</script>
</body>
</html>
you can include one js file into another js file by doing something like this in the begginig of your js file:
document.write("<script type='text/javascript' src='another.js'></script>");
The best approach in your situation is using of compiler of some kind. The greatest one is Google Closure Compiler. This is part of Google Closure Libraty which has structure similar to what you described.
This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 9 years ago.
I'd like to know if it is possible to include a .js file within another .js file?
The reason for me wanting to do this is to keep client includes to a minimum. I have several .js files already written with functions that are needed by the client. The client would have an html file which he/she manages with a .js file include (my .js file).
I could re-write a new .js file with all the functions in it or, to avoid doing double work, figure out a way to write a .js file that includes other .js files.
I basically do like this, create new element and attach that to <head>
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.
x.onload=callback_function;
The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.
Alternatively, you can use DOM to create a <script> tag and set the src property on it then append it to the <head>. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load event on that script tag.
This function is based on the functionality of jQuery $.getScript()
function loadScript(src, f) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
var done = false;
script.onload = script.onreadystatechange = function() {
// attach to both events for cross browser finish detection:
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
if (typeof f == 'function') f();
// cleans up a little memory:
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
// example:
loadScript('/some-other-script.js', function() {
alert('finished loading');
finishSetup();
});
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this:
http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.
Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.
You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.
I use #gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:
if (horus.script.broken) {
document.writeln('<script type="text/javascript" src="'+script+'"></script>');
horus.script.loaded(script);
} else {
var s=document.createElement('script');
s.type='text/javascript';
s.src=script;
s.async=true;
if (horus.brokenDOM){
s.onreadystatechange=
function () {
if (this.readyState=='loaded' || this.readyState=='complete'){
horus.script.loaded(script);
}
}
}else{
s.onload=function () { horus.script.loaded(script) };
}
document.head.appendChild(s);
}
where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).