How to load one JavaScript file from another? - javascript

How do you load one JavaScript file from another JavaScript file, like CSS?
In CSS we use write #import url("mycss.css");.
Is there any way to do it in JavaScript?

There's no #import-ish function/method in Javascript, but you can simply append a script to the <head> tag like so:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/path/to/js/file';
document.getElementsByTagName('head')[0].appendChild(newScript);
Or like Edgar mentioned right before me you can use jQuery.

Yes. If you want in pure JavaScript, you have to create dynamically a script tag, and append it to the document.
Yes. If you use the jQuery library, you can use the $.getScript method.
$.getScript("another_script.js");

Just because no-one has mentioned it yet, there's another option, which doesn't require any fancy libraries or tricky coding, document.write. In principal, it would look like this, although see below for a caveat:
document.write('<script src="myscript.js" type="text/javascript"></script>');
This will be executed upon completely parsing the script tag, and if you put your script tag in the head, the new script tag will also be in the head, right after the one being executed. Take care to execute it directly rather than when the document has been loaded (as in a $(function(){}) callback. This is what I use:
(function(){
function load(script) {
document.write('<'+'script src="'+script+'" type="text/javascript"><' + '/script>');
}
load("script1.js");
load("script2.js");
load("etc.js");
})();
The enclosing function is just there to not pollute the global namespace.
The caveat (and why the 'script' that is broken up above) is that there may be no ending script tags within a script tag, the HTML parser doesn't know it's part of the script. There's an other question on that subject.

Javascript itself doesn't provide any help with modularization other than the ability to eval a string. But this is a common-enough need that most big javascript frameworks have come up with their own solutions, and more recently, there has been an effort to standardize those APIs in the requirejs project. If you're using a framework like Dojo or jQuery, you're probably just best off learning to use their facilities, but if not, requirejs is a lightweight standalone tool. You basically just add
<script data-main="scripts/main" src="scripts/require.js"></script>
to your <head> section, and then put your own javascript inside some wrapper code like this (stolen from the require.js site):
require(["helper/util"], function() {
//This function is called when scripts/helper/util.js is loaded.
require.ready(function() {
//This function is called when the page is loaded
//(the DOMContentLoaded event) and when all required
//scripts are loaded.
});
});

use const dataName =require('./fileName.js');

Related

Using socket.io with a standalone javascript file

I'd like to use socket.io in a javascript file. How can I do this?
The only way I currently know of using socket.io, as a client is doing
<script src="[server?]/socket.io/socket.io.js"></script> inside an html file.
Including a javascript within a javascript file is not naturally accomplished, because it's not really needed in most scenarios (you just include them both on your html page, for example). You probably have to rethink the way you're executing javascript, but I do believe there is a library designed to this (for whatever reason that may be).
include.js I think it is called.
EDIT: and in the event you're thinking dynamically adding javascript, you can just create a script element and append it to document.head. Um, for example:
document.head = document.head || document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src','http://my/src/file');
document.head.appendChild(js);
...just off the top of my head.
In my html file I did:
<script src="http://[node server]:[port]/socket.io/socket.io.js"></script>
`
and in my .js file, I did
io.socket = io.connect('http://[node server]:[port]');
and it worked.
I suppose "a standalone javascript file" is inaccurate, because I'm building a web front-end. I meant that it was just a .js file with nothing like node.js running it.

Script src javascript

What is the difference between this code
var head=document.getElementsByTagName('head')[0]
var script=document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', "http://your-script.com/address-here.js")
head.appendChild(script)
and this code
<script type="text/javascript" src="http://your-script.com/address-here.js">
</script>
Thank you.
The javascript at the top is going to append a new element to the first head tag of the document that should equal out to <script type="text/javascript" src="http://your-script.com/address-here"></script> (or close to). The only difference is that the browser will load the HTML version as soon as it comes across it whereas the JS won't be loaded until the element is done being appended.
As #lostsource mentions this would be typically used to load a dependency script or used to bring in polyfills, e.g. if(!someJSFeatureIWant) {//import the script here}.
The first one is normally used as a way to include additional Javascript files required by a Script. (it is just dynamically creating a <script> tag like the second code sample)
For example you might include the core functionality in a main.js file, then depending on user interactivity you decide to include other scripts. (eg. graphics.js, forms.js etc..)
The same approach is also used to make JSON-P requests by dynamically including a url which returns a JSON 'padded' response. With the main advantage over iframes and regular XHR requests being that <script> tags are not affected by the same origin policy.
One is JavaScript and will add a script to the DOM after it has been created. The other is HTML and will add a script to the DOM while it is being created.
Essentially, both load a js file, but the first sample effectively creates the other on demand.
var head=document.getElementsByTagName('head')[0]
var script=document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', "http://your-script.com/address-here.js")
head.appendChild(script)
You would generally use this for loading external code into a page on the run (after it is created). This specific syntax used in the example also pollutes the global scope and should not be used as is.
<script type="text/javascript" src="http://your-script.com/address-here.js">
</script>
This is the natural HTML syntax for loading script files. If the page code is under your control, you have no reason to ever use anything other than this unless in special circumstances that demand it or for optimisation purposes.

What is the most ideal way of loading javascript files?

What is the most ideal way of loading javascript files? Also, I want to make sure that order of the javascript files should be maintained. If I have
<script src="javascript1.js">
<script src="javascript2.js">
on my page, then javascript1.js should load before javascript2.js
Thanks.
EDIT: Thank you for your answers, but mine question is not only related with the order of js files. I want to load js files as quickly as possible without using any 3rd party js library. The solution which is similar can be found at www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/, but using this does not guarantee the order of the files for me, atleast.
There is no single "best" way of loading Javascript files. Different ways work best in different scenarios.
The normal way of loading Javascript files is to put the script tags in the head tag.
You can put some script tags inside the body tag instead, to make them load later. One common reason for this is to make the content of the page display without having to wait for the script to load.
The scripts are executed in the way that the tags are placed in the code. The execution of the code below a script tag waits for the Javascript to be executed first.
In your question you say that you want one script to load before the other, which can't be guaranteed by just using script tags in the code. Then you would have to generate the second script tag in the first Javascript and use document.write to put it in the page. To make the scripts execute in that order, you can just use your script tags the way that you do, and the order is guaranteed.
Note: You should specify the type attribute in the script tags, so that the tags validate without errors. You need to include the closing tag for the script tags.
<script type="text/javascript" src="javascript1.js"></script>
<script type="text/javascript" src="javascript2.js"></script>
As others have said, the scripts are loaded in order of placement on the page (unless they are wrapped in javascript to be loaded in later)
Putting the script tags at the bottom of the page can assist with the loading process for both old and new browsers. Although some scripts might (like modenizer) need to be loaded earlier on in the process. A good example can be seen at http://html5boilerplate.com/ on the index code sample.
Edit:
Following your edit, there is this info which can help
<script type="text/javascript">
document.writeln("<script type='text/javascript' src='Script1.js'><" + "/script>");
document.writeln("<script type='text/javascript' src='Script2.js'><" + "/script>");
</script>
The full documentation on this can be read here (including crevets of other methods) http://blogs.msdn.com/b/kristoffer/archive/2006/12/22/loading-javascript-files-in-parallel.aspx
HTML is a top down procedural language so anything that is posted first gets executed first. Hence the order which you wrote is correct.
Your web browser will execute javascript files in the order they are declared, so in your example:
<script src="javascript1.js">
<script src="javascript2.js">
javascript1.js will be executed before javascript2.js.
As for the most ideal way, this is all very subjective. I prefer progressive enhancement when using javascript so declare my javascript as the last element on a page, since it is not required for the site to function, any user can see the content and use the site even while the javascript is downloading.
I also prefer bundling all my scripts together, in a minified form, so the browser only has to make one request to get my javascript.
There is a school of thought that using parallel loading is good. This means the scripts are loaded like the GA snippet provided by google by using JS. A good way of doing this is to use modernizr. This script enables you to load the scripts when they are needed. You would need to include the modernizr script in the traditional way and then write some JS to load the other script when required.
The Best Answer Can Be Found Here:Here:http://www.html5rocks.com/en/tutorials/speed/script-loading/
Ideally do this if you need to load them in some particular order (In case of dynamically added scripts):
`
['//other-domain.com/1.js',
'2.js']
.forEach(function(src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});
`
And this for no order:
`
['//other-domain.com/1.js',
'2.js'
].forEach(function(src) {
var script = document.createElement('script');
script.src = src;
document.head.appendChild(script);
});
`
But if you just need static scripts then just ado this at the end of your body as suggested by many others:
`<script src="//other-domain.com/1.js"></script>
<script src="2.js"></script>`

How to #include in javascript?

Say my javascript scripts aren't embedded in html/xml... I want to write a small library of helper functions to use in my scripts. Obviously there has to be an "#include" or "require" keyword in javascript, but I can't find any. Anything I could with Google relies on the code being part of html/xml, which doesn't help in my case.
What should I do?
I believe you mean to write some sort of dependency tracking framework for your javascript files and use a process called "Lazy-Loading" to load the required JS file only when it's needed.
Check out Using.js, it seems to do what you need.
Also you might want to check addModule from YUILoader. It allows loading non-YUI framework components on the fly.
There actually isn't a really #include or require in javascript. You're actually supposed to handle all the dependencies yourself. I've seen people do a hack where they do a document.write to include other javascript files.
in the case you care, here there is a version of include that uses the document object via it's DOM interface:
function include(aFilename) {
var script = document.createElement('script');
script.src = aFilename;
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script)
}
the problem is that you must include this function in all your source file that needs includes... :P :P
to include a js file in html:
<script type="text/javascript" src="..."></script>
it should be in the page head for correctness.

What is the best way of including a JS file from JS code?

What is the recommended way of including a Javascript file from another Javascript file?
Most people add the JavaScript file to the head of the document:
<script type="text/javascript">
var newfile=document.createElement('script');
newfile.setAttribute("type","text/javascript");
newfile.setAttribute("src", '/myscript.js');
document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
There are libraries that'll do this for you. You can also add a script tag to your document pointing to the file you want to load (from js), which is simplest, but has problems.
http://developer.yahoo.com/yui/yuiloader/
http://www.appelsiini.net/projects/lazyload
Edit: I see a lot of answers that add a script tag to the head of your document. As I said this simple solution has a problem, namely you won't know when the browser has finished loading the script you requested, so you wont know when you can call this code. If you want to use a solution like this you should also add a callback somehow to tell you when the required code was loaded.
jQuery has getScript() function. Also note that Lazy Load mentioned above is only for images. Not for JavaScript files.
$.getScript(url, [callback]);
How about this:
(original link)
<script type="text/javascript">
// Function to allow one JavaScript file to be included by another.
// Copyright (C) 2006-08 www.cryer.co.uk
function IncludeJavaScript(jsFile)
{
document.write('<script type="text/javascript" src="'
+ jsFile + '"></scr' + 'ipt>');
}
</script>
and then to include a second JavaScript file simply add the line:
IncludeJavaScript('secondJS.js');
The page that came from includes some gotchas that arise from this approach, so it's worth looking at before using the method.
Theres also an function built into Scriptaculous that is very easy to use.
Scriptaculous.require("path/to/script.js");
Worth knowing, since Scriptaculous is a very common javascript library these days.
Dojo does it using dojo.require():
dojo.require("your.module.name");
Normally this is a synchronous operation done with XHR. But if you use the xDomain build it will be asynchronous and dojo.addOnLoad() will be raised when the script is loaded.
Read more about it:
Modules
What dojo.require does
Quickstart: custom builds (includes xDomain explanation)
Cross-domain Dojo (specifically dedicated to xDomain stuff).

Categories