I have created a combined.js file page with all my inline and other scripts into one file...
How can I load these scripts asynchronously into my page? - I have done this because Google and Yahoo recommends this to speed-up my website loading.
I have already placed the file in my footer.php (I am using wordpress using wp_enqueue_script) but without async or defer tags, as it seem like I will have to hardcode these into my files?
In HTML5 you can use the 'async' attribute you can see here the support for it:
<script async src="myJavascript.js"></script>
The old way to do it, is like this:
<script>
var res = document.createElement('script');
res.src = "myJavascript.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(res, script);
</script>
This way has more support than you will ever need.
Related
We made a website through webnode.nl, because we hadn't enough time to make a website using html. Now we added a widget using a external site using a script tag with the link to this site. But through this widget the page is loading slow. Now I had the idea to run the script after the page is loaded. But I can't access the code of the widget and I can't access the html of the website. I can only access the code block in which I pasted the script tag.
The script tag:
<script type="text/javascript" src="http://mycountdown.org/countdown.php?cp2_Hex=d21a1a&cp1_Hex=F9F9FF&img=-3&hbg=&fwdt=420&lab=1&ocd=My Countdown&text1=Valentijnsdag!&text2=valentijnsdag!&group=My Countdown&countdown=My Countdown&widget_number=3015&event_time=1455408000&timezone=Europe/Amsterdam"></script>
Can someone help me?
PS: English is not my first language, so I don't know if my English is correct
Place it at the end of the <body> and add async to the script tag i.e.
<script async src=""></script>
More info here: http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html There is also the defer attribute.
Typically you want to use async where possible, then defer then no
attribute. Here are some general rules to follow: If the script is
modular and does not rely on any scripts then use async. If the script
relies upon or is relied upon by another script then use defer. If the
script is small and is relied upon by an async script then use an
inline script with no attributes placed above the async scripts.
Edit
You may be better using Defer:
defer downloads the file during HTML parsing and will only execute it
after the parser has completed. defer scripts are also guarenteed to
execute in the order that they appear in the document.
if you can write script blocks then write the following in whatever you are allowed to use.
<script>
// Create a <script ...></script> element
var widget = document.createElement('script');
// Set src="URL_of_widget"
widget.setAttribute('src', 'http://mycountdown.org/countdown.php?cp2_Hex=d21a1a&cp1_Hex=F9F9FF&img=-3&hbg=&fwdt=420&lab=1&ocd=My Countdown&text1=Valentijnsdag!&text2=valentijnsdag!&group=My Countdown&countdown=My Countdown&widget_number=3015&event_time=1455408000&timezone=Europe/Amsterdam');
// Set async
widget.setAttribute('async', 'async');
// Insert <script> as the last element child of <body>
document.body.appendChild(widget);
</script>
I have included 3 external js files at the end of body.
Suppose my document already contains a js named as insertlibs.js and here is the code
var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script1);
// Similar way to include underscore
var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);
But what is happening sometimes, it is throwing an error that $ is not defined and I tried to debug in Firefox and there is a parallel download occurring for jquery and backbone and sometimes backbone library getting download earlier than jQuery which is causing this error.
As far as i know that if a script tag is included, it will block further request So as soon as I add jquery in dom. I am confused about the workflow here happening.
So i have found the solution, I merged both the js and making a single call which is working perfectly but that does not explain me the flow happening in above case. Please help.
This is because you are attempting to include backbone without ensuring that jquery has been completely loaded. To correct this, you can use the script's onload attribute to attach a callback which will be fired when jquery is loaded.
For ex:
var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
// add an onload handler
script1.onload = function() {
// load the rest of the scripts here
var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);
}
document.getElementsByTagName('Body').item(0).appendChild(script1);
As far as i know that if a script tag is included, it will block further request
No, the blocking / synchronous download is only when the tags are right in the parsed HTML (or are inserted via document.write during the parse); dynamically DOM-appended scripts load asynchronously and in parallel.
To do that but ensure that scripts are executed when their dependencies are met, you need to use AMD loaders.
I want to use Head JS to dynamically load all of the other scripts for my pages. I'm planning on using the version hosted by CDNJS to take advantage of the better caching, decreased latency, etc.
I have no reason to think CDNJS is going anywhere, but even for Google CDN hosted files like jQuery, I like to include a fallback. When I'm using jQuery though, the files are included at the end of the <body> tag. Due to the nature of Head JS, I need to include it in the <head> of my page.
In the <body> I would use two lines like this:
<script src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.96/head.min.js"></script>
<script> window.head || document.write('<script src="js/libs/head-0.96.min.js"><\/script>') </script>
Can I use this same set of lines in the head as a fallback? Won't document.write() overwrite my entire page? Don't scripts load differently when they exist in the <head> due to the order that browsers parse the DOM?
I'm still pretty new to this, so any guidance would be hugely helpful! Thanks!
As you probably already know, you won't be testing for window.jQuery but some function included in head.js.
Additionally, you're right that you may not want to use document.write() twice here.
Instead of document.write(), try this:
function appendScript(url) {
var head = document.getElementsByTagName('head')[0];
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.src = url;
theScript.onreadystatechange = callback;
theScript.onload = callback;
head.appendChild(theScript);
}
For the url, use your local fallback.
I want to load an external javascript after page is loaded. Actually the javascript contains source for an ad and its making page load slow. All I want is to delay loading & execution of ads to make sure fast page load.
thanks,
Bilal
You may just use this script at the last tag of your body block:
<script type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://yourdomian.com/your_script.js');
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
var script=document.createElement('script');
script.type='text/javascript';
script.src=url;
$("body").append(script);
Courtsey
$("#selector").click(function(){
$.getScript("YourScript.js");
});
Then Run what is implemented in that script
I would look at using asynchronous Javascript loading. There are frameworks for this such as requireJS.
Without using something like jQuery getScript() and a promise or a proper loading library like requireJS, the script can be included in the page, but will load async so there's no guarantee it will be ready when you need it. If you're already using jQuery, the simple answer is then:
$.getScript( scriptUrl ).then( function() {
//do this ONLY after the script is fully loaded
});
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>`