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.
Related
Is there anyway of importing multiple javascript files in HTML without having to specify each file?
<script src="js/toolkit/Toolkit.js"></script>
<script src="js/toolkit/Viewable.js"></script>
<script src="js/toolkit/Overlay.js"></script>
ie. can I specify something like js/toolkit/* ?
I have 50+ javascript files that i have to import, and to specify each file seems very time consuming.
Including a JavaScript file in another JavaScript file is common in web development.
Because many times we include the JavaScript file at run time on the behalf of some conditions.
So, we can achieve this using JavaScript as well as using jQuery.
Method 1: Use JavaScript to include another JavaScript file
Add the following function in your web page.
function loadScript(url)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
just call the below loadScript function, where you want to include the js file.
loadScript('/js/jquery-1.7.min.js');
Method 2: Use jQuery to include another JavaScript file.
Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Just call the getScript function functions.
jQuery(document).ready(function(){
$.getScript('/js/jquery-1.7.min.js');
});
How to include a JavaScript file in another JavaScript File
There's a way:
You can create a javascript function that takes the path as a parameter and creates these HTML lines:
<script src="js/toolkit/Toolkit.js"></script>
<script src="js/toolkit/Viewable.js"></script>
<script src="js/toolkit/Overlay.js"></script>
And you'll just have to call this:
loadLib("toolkit/Toolkit");
loadLib("toolkit/Viewable");
loadLib("toolkit/Overlay");
But this is not recommended because the load time will be increased due to the number of HTTP requests.
You should better use something in the server side to put everything in the same file.
No you can't do it. And by the way this is not good idea to load all 50 separate files. Consider compressing them in one single script to improve performance and decrease page load time.
You can setup grunt to watch the folder of the scripts and concat/minify them into a single file, then you just have to include that in your HTML file.
You will need to specify each file for the browser to know what to retrieve, but depending on the IDE you are using, there may be shortcuts for doing this, (Visual Studios allows you to drag and drop script files into the html to add references).
During development, you want to do just as your doing by keeping the files separate for troubleshooting, but in production, as others have commented, its very good practice to minify your code and combine them into one file. That makes it only one call, and can reduce your overhead significantly.
I recommend you to use JSCompress. It will compress all your javascript code into one single javascript file.
import "./angular.min.js"
import "./jquery-3.6.0.min.js"
import "./app.js"
<script type="module" src="js/importJS.js"></script>
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>`
I was reading up on non blocking ways of loading javascript.I came upon some interesting concepts, especially a new one to me. The script defer attribute.
I know about dynamically creating scripts and inserting them to the head of the document, which i have a function for.
for example:
function loadJS(loc){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = loc
}
I have seen this defer attribute and Im not sure on how to use it and what its main advantages/disadvantages are?
Thanks in advance guys!
I've been looking for similar answers and was about to post a question when I found this stackoverflow question -- and yours.
So here is what I've found out:
The script defer approach hints to a browser to wait until the document has finished loading before executing the script. BUT it still loads the script first (assuming that they're located in the HEAD of the document).
jQuery has a .getScript() method which can be used to load any number of scripts whenever and wherever needed. You could even apply it to an onClick event on a link for instance!
There are also several libraries aimed at dynamic, non-blocking loading such as LABjs, RequireJS or HEADjs.
I guess it's up to you which approach you choose, if you're only on a small project and are already using and/or used to using jQuery then I'd go with that. Otherwise maybe check out one of the libraries.
Just to state again however that as best as I can tell DEFER will not prevent page blocking when loading scripts. But a typical and very simple solution to this is to include all your scripts in the page footer rather than the HEAD.
People please feel free to correct me if I'm wrong on any of the above! -- Thanks
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');
I am creating a piece of JavaScript to be deployed to sites that are, at the moment, unknown to me.
This piece of code is supposed to do something that would be so much easier if I could just do it with jQuery, but I can't include any external libraries in this code because:
I can't load other files, just the one JavaScript file that I write.
Any external library might conflict with the unknown client site's code (they might already have loaded that same library into their site).
I need the file to be downloaded as fast as possible.
Now my question is: Is there a tool that would help me extract just the specific code-paths my code uses from the external library (jQuery) so that I could embed them directly into my code as part of it (using namespaces, etc.)?
Or it could be that my question is even wrong to begin with.
I know it conflicts with the first caveat but you could include jquery dynamically in your code by writing out the script element to a CDN e.g.
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js
var headID = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js';
script.onload = function() { initialiseJQuerySpecificCode(); };
headID.appendChild(script);
function initialiseJQuerySpecificCode() {
jQuery.noConflict();
//more jquery code
jQuery(document.ready(function() {
//initialisetion code
}));
};
Loading from CDN means that many users will already have it in their cache. Also - the minified version is very small anyway.