I've been reading a lot about jQuery.ready() will slow your page down. My website has a bunch of code running inside jQuery.ready() as many websites do.
</body>
<script>
jQuery(document).ready(function() {
// Do some event binding and initialization.
});
</script>
I place this script at the end of <body> tag but I wrapped the code inside DOM ready just to be safe.
Now I test my page with http://www.webpagetest.org/ and I noticed that the domContentLoaded time is as follows:
domContentLoaded
4.987s - 5.317s (0.330s)
Now I experimented by removing jQuery.ready(function() {}); to be just
</body>
<script>
// Do some event binding and initialization.
</script>
And I test the page again. Here's the result.
domContentLoaded
3.772s - 3.915s (0.143s)
The execution goes down to just 0.1s which is about ~187ms. Am I right to assume that the execution time goes down because the code is not executed inside jQuery.ready and what does this mean in terms of performance gain, e.g perceived performance. Do users feel that the page loads quicker?
isn't domContentLoaded the same event trapped by $.ready? If webpagetest's timer is taking longer when the main script is running at $.ready, that could just indicate that more threads are competing for resources at that time. it makes sense that allowing any setup and initialization that can run before that event to do so will make all of the setup that happens at document ready run smoother...
domContentLoaded in webpagetest is document.ready in jquery
fire your code on onLoad event to improve performance
if("undefined"==typeof(addOnload)){function addOnload(a){if("undefined"!=typeof(window.attachEvent)){return window.attachEvent("onload",a)}else{if(window.addEventListener){return window.addEventListener("load",a,false)}}};}
call your function on onload event
addOnload(fnName);
Related
I was using $(window).load(function(){}); for my projects until somewhere I saw that somebody said we could just use $(function(){}); and they would perform identically.
But now that I have more experience I have noticed that they are not identical. I noticed that the first piece kicks in a little bit after the second piece of code.
I just want to know what's the difference?
$(document).ready(function(){})
will wait till the document is loaded(DOM tree is loaded) and not till the entire window is loaded. for example It will not wait for the images,css or javascript to be fully loaded . Once the DOM is loaded with all the HTML components and event handlers the document is ready to be processed and then the $(document).ready() will complete
$(window).load(function(){});
This waits for the entire window to be loaded. When the entire page is loaded then only the $(window).load() is completed. Hence obviously $(document).ready(function(){}) finishes before $(window).load() because populating the components(like images,css) takes more time then just loading the DOM tree.
So $(function(){}); cannot be used as a replacement for $(window).load(function(){});
From the jQuery docs itself.
The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
window.onload = function(){ alert("welcome"); }
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.
To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:
$(document).ready(function(){
// Your code here
});
Now,
$(window).load(function(){}); is equal to window.onload = function(){ alert("welcome"); }
And, $(function(){}); is a shortcut to $(document).ready(function(){ });
I think , this clears everything :)
$(window).load from my experience waits until everything including images is loaded before running where as $(function() {}); has the same behaviour as $(document).ready(function() {});
Please someone correct me if I am wrong.
The second is/was a shortcut for $(document).ready(), which should run before window's load event.
Note that $(document).ready() is the preferred way of binding something to document load; there are a couple other ways of doing it like the one you showed, but that's preferred.
In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?
For example, if I want to have a pop-up, should I write (directly inside the <script> tag):
alert("hello!");
Or:
window.onload = function() {
alert("hello!");
}
Both appear to run just after the page is loaded. What is the the difference?
The other answers all seem out of date
First off, putting scripts at the top and using window.onload is an anti-pattern. It's left over from IE days at best or mis-understandings of JavaScript and the browser at worst.
You can just move your scripts the the bottom of your html
<html>
<head>
<title>My Page</title>
</head>
<body>
content
<script src="some-external.js"></script>
<script>
some in page code
</script>
</body>
</html>
The only reason people used window.onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.
The hacky workaround was to use window.onload to wait for the rest of the page to load. Moving your script to the bottom also solved that issue and now there's no need to use window.onload since your body and content will have already been loaded.
The more modern solution is to use the defer tag on your scripts but to use that your scripts need to all be external.
<head>
<script src="some-external.js" defer></script>
<script src="some-other-external.js" defer></script>
</head>
This has the advantage that the browser will start downloading the scripts immediately and it will execute them in the order specified but it will wait to execute them until after the page has loaded, no need for window.onload or the better but still unneeded window.addEventListener('load', ...
window.onload just runs when the browser gets to it.
window.addEventListener waits for the window to be loaded before running it.
In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:
window.addEventListener('load',
function() {
alert('hello!');
}, false);
Here's the documentation on MDN.
According to it:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
Your first snippet of code will run as soon as browser hit this spot in HTML.
The second snippet will trigger popup when the DOM and all images are fully loaded (see the specs).
Considering the alert() function, it doesn't really matter at which point it will run (it doesn't depend on anything besides window object). But if you want to manipulate the DOM - you should definitely wait for it to properly load.
That depends on if you want it to run when the script element is encountered or if you want it to run when the load event fires (which is after the entire document (including such things as images) has loaded).
Neither is always right.
In general, however, I'd avoid assigning functions directly to onload in favour of using addEventListener (with compatibility libraries if I needed to support older browsers).
The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert, it doesn't matter. Let's say, however, you were targeting a div that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.
document.ready is a great alternative to window.onload if you're using jQuery.
See here: window.onload vs $(document).ready()
You have three alternatives:
Directly inside the script tag runs it as soon as it is parsed.
Inside document.addEventListener( "DOMContentLoaded", function(){}); will run it once the DOM is ready.
Inside window.onload function(){}) will run as soon as all page resources are loaded.
Jquery has a ready method:
$(document).ready(function(){
// my code
})
It will execute my code when dom is ready.
I have a question, if I put all my scripts after </body>, e.g.
<html>
<body>
// all kinds of html tags
</body>
<script src="/path/to/jquery.js"></script>
<script src="/path/to/all-javascript-compressed-in-one-file.js"></script>
</html>
Do I still need to write $(document).ready()? Is the dom already ready after </body>?
Usually, the scripts are added just before </body>, not after it – the HTML won't validate otherwise; no content can appear outside <head>, or <body>, as noted by Šime Vidas on his comment.
That being said, technically the DOM is not considered ready yet at that point (as the browser is still parsing the <body>), but already contains all elements from the body. Thus, it's safe to skip $(document).ready().
Doing that will execute your initialization scripts earlier, since there is some delay before the actual DOMContentLoaded event is fired. That means a faster page load, and a better user experience.
You might be interested in this related discussion about forcing the jQuery ready event.
In a word, no. The dom is considered "ready" when the dom tree is available, if your javascript is the last thing on the page, then everything before it is "ready", as web pages are "loaded" from the top down.
At the core, this is a javascript question but I'm interfacing the event with jQuery.
Here's an example case:
<html>
<head>
<script src="waiting_on_ready.js" />
</head>
<body>
<script src="http://somewhere.com/not_cached.js"></script>
</body>
</html>
Does the $.ready callback in waiting_on_ready.js have to wait for not_cached.js to be loaded? Does it wait for not_cached.js to be executed?
Yes and yes.
The execution of <script> elements is synchronous except when using the HTML5 "async" attribute. The synchronous execution of JavaScript is required (unless otherwise requested not to be) because the JavaScript can modify the document stream through document.write, etc. (However, the actual fetching of resources may be in parallel.)
Happy coding.
Ready fires when all DOM elements are ready for manipulation.
When the browser comes across a script element, DOM parsing stops until the script has been executed, so because of how it all works, it fires after all scripts are loaded.
$(document).ready() would not be triggered prior to not_cached.js to be loaded and executed (assuming execution in not_chached.js is synchronous)
the $.ready script executes after the page is fully loaded, as the onload event does, however if an inline script is found then it is executed.
What is the difference between DOMContentLoaded and load events?
From the Mozilla Developer Center:
The DOMContentLoaded event is fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images,
and subframes to finish loading (the load event can be used to detect
a fully-loaded page).
The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.
DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.
See the difference yourself:
DEMO
From Microsoft IE
The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.
From Mozilla Developer Network
The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).
DOMContentLoaded==window.onDomReady()
Load==window.onLoad()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
See: Using JQuery Core's document-ready documentation.
For a full understanding I recommend to read the following articles:
What is DOM and CSSOM: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/constructing-the-object-model
What is the render tree: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction
How is everything related to DOMContentLoaded, load and first print:
https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp
In Short:
The DOMContentLoaded event is fired when the DOM is created (see link 1 for more what the DOM is) and the load event is fired when the DOM, CSSOM and all other resources are loaded. If you don't have Javascript, then the order that your webpage is loaded may look like this:
Or in the words of an inspection window, the DOMContentLoaded event will be fired much earlier then the load event (blue line represents DOMContentLoaded, red line represents load event):
However, if you use Javascript (that is not async or defer) then the DOM creation will wait for the JS to load. Since JS also modifies CSS, JS will wait for the CSSOM to load.
Since this is the most common situation, the creation of the DOMContentLoaded event actually has to wait in most scenarios for the style-sheets to be loaded as well.
The loading chain look like this then:
So the main difference between DOMContentLoaded and load is, in this situation, only the loading time of the image, which can be downloaded in parallel to your style-sheets and JS.
Note that this doesn't happen if you use async or defer for your JS:
domContentLoaded: marks the point when both the DOM is ready and
there are no stylesheets that are blocking JavaScript execution -
meaning we can now (potentially) construct the render tree. Many
JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution
took.
loadEvent: as a final step in every page load the browser fires
an “onload” event which can trigger additional application logic.
source
Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff() function whether DomContentLoaded triggers before or after your external JS files.
// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);
function doStuff(){
//
}
if(isIE){
// play it safe, very few users, exec ur JS when all resources are loaded
window.onload=function(){doStuff();}
} else {
// add event listener to trigger your function when DOMContentLoaded
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded',doStuff);
} else {
// DOMContentLoaded already loaded, so better trigger your function
doStuff();
}
}
The answer with the highest number of approvers is wrong, at least in the higher version of Chrome 80+.
1、DOMContentLoaded does not fire until the CSS and JavaScript are executed and the DOM is parsed (the document has been loaded)
2、The window.onload event, which does not fire until all network resources, such as CSS and JavaScript, have been loaded, and the DOM has been parsed (the document has been loaded)
Based on Chrome 80+ test results:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOMContentLoaded , load</title>
<link href="http://localhost/public/css?sleep=5000" rel="stylesheet">
<!-- 5000 milliseconds after the URL request the server begins to respond -->
</head>
<body>
<img src="http://localhost/public/img?sleep=8000">
<!-- 8000 milliseconds after the URL request the server starts responding to the resource -->
<script>
document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded OKOK')
})
window.addEventListener('load', () => {
console.log('window load OK')
})
</script>
<script src="http://localhost/public/js?sleep=2000"></script>
<!-- 2000 milliseconds after the URL request the server begins to respond -->
</body>
</html>
Test execution results:
After the page is running for 5 seconds, console.log('domContentLoaded OKOK'), is carried out
console.log(' Window Load OK') starts running at 8 seconds