Recently I saw that you could use either
$('document').ready(function() {
//Do Code
});
or
$('window').load(function() {
//Do Code
});
for jQuery.
However, they seem the same to me! But clearly aren't.
So my question is: Which one should I use for a website sort of based on animation and async? And also which one of the two is generally better to use?
Thanks.
$('document').ready runs the code when the DOM is ready, but not when the page itself has loaded, that is, the site has not been painted and content like images have not been loaded.
$(window).load runs the code when the page has been painted and all content has been loaded. This can be helpful when you need to get the size of an image. If the image has no style or width/height, you can't get its size unless you use $(window).load.
Well first of all you may want to consider using the "ready" event, which you can handler like this:
$().ready(function() {
...
});
Or, more succinctly and idiomatically:
$(function() {
...
});
The "load" handler really relates to an actual event, and can be handled on several different sorts of elements: <img> and <iframe> for example. The "load" event at the document or window level happens when all of the page's resources are loaded. The (synthesized, in some browsers) "ready" event however happens when the page DOM is ready but possibly before things like <img> contents.
Another option is to simply put your <script> tags at the very end of the <body> or even after the <body>. That way the scripts have the entire DOM to work with, but you don't have to worry about any sort of event handling to know that.
Related
First at all, I want know the difference between the $(document).ready and the $(window).load, then I know this.
But, I have some new questions.what is the ready event, what is the detail. what is the load event.
I have find the description of load event in the HTML spec.
But I can't find the description of the ready event.
ready() is an abstraction implemented by jQuery based on DOMContentLoaded.
load() (Note this jQuery method is depreciated) is based on window.onload.
The MDN articles link to the specification.
In JavaScript window is one of core object and defines several useful events e.g. onload, before jQuery comes, if want to execute any code, once DOM is loaded completely, we use window.onload event
There is a problem with window.onload , it not exactly executed when DOM is loaded but it executes after all content including big images are loaded completely. Browser normally delay executing onload code, until all page content is loaded, because of this user can see significant delay between they first see the page and the time that code inside onload get executed, this delay is particularly notable, if your page content heavy images, flash videos or other heavy content with low bandwidth internet connection.
jQuery solves this problem by introducing ready event, you might have seen code like below in several JavaScript files or HTML pages :
$(document).ready(function(){
alert("Inside jQuery ready method");
});
here $() is a shortcut for jQuery() function, and we wrap document object into jQuery object to use ready() method. We are passing an anonymous function to ready() method, which will be executed once DOM is loaded. It doesn't wait till all DOM content available e.g. images. By the way, instead of using $(document).ready() function, you can also use following short-cut, which has same effect :
$(function() {
alert("shortcut for document.ready method in jQuery");
});
Apart from faster execution, one of the key advantage of jQuery ready method over JavaScript window onload event is that, you can use them multiple times in your page, unlike onload event, which can only be bind to a single function. Browser will ensure to execute all document.ready code to execute in the order, they are specified in the HTML page.
Hope this will be useful for you.
Thanks
I read here in SO about preloading the array of images for faster loading of the web page so that when the application needs them to be shown, that would have loaded and can be shown instantly. But my doubt was where to include the code snippet:
at the bottom of page or
at the start (<head>)?
As, I also read that in order for fast loading one should include all the javascripts at the bottom.
Which will be a better way? Or do I have to compromise on both the ways?
The javascript code:
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
preload([
'images/bg.jpg',
'images/logo1.png',
]);
</script>
Even though all the other answers are inherently correct. They don't seem to address you directly.
Your script is not making use of any DOM elements. Which means that waiting for the DOM to load is not a concern at all.
The halt of the layout rendering while downloading a <script/> is always a concern (unless you use new HTML5 capabilities such as async), that's why they prefer to place it before </body>.
By placing it before </body>, your rendering will not be halted. Performance-wise, iterating such a tiny array may only be a micro-optimization.
By the way, you don't need to wrap the array in $() to use .each(), you should use $.each.
function preload(arrayOfImages) {
$.each(arrayOfImages, function(index, image){
$('<img/>')[0].src = image;
});
}
Generally, put your function calls and everything that you want to do after the page finishes loading inside
$(document).ready(function() {
// Handler for .ready() called.
});
(See Docs).
This also applies to your call to preload(...).
As you use $('<img/>')[0].src = this, the browser will cache the image according to this comment: Preloading images with jQuery
Edit: The position of the <script/> tag in your DOM tree plays only a minor role, as Konstantin pointed out.
The top and the bottom of the HTML page is relevant because that is how the browser reads your page. Stuff on the top gets done before the stuff on the bottom.
In regards to image pre-loading you should do it in the top of the page in the <head>. Why? Because you don't need to use it yet. The rest of the page isn't ready and chances are that the place where you want to put the image doesn't even exist just yet.
We usually put JavaScript on the bottom of the page because we want to do something when the DOM is ready. You can put it on the top as well! But you would have to NECESSARILY use the $(document).ready(function(){}); in order to be certain that it would work as intended.
So, initiate your pre-loads on the top (or by using window.onload) while the rest of the page is loading as well. You wont really get much benefit out of doing it on the top unless you do it using CSS or if you bind the load event of a particular div that occurs on the top of the page and pre-load your images there.
Why not making a DIV on the very begining of the BODY section and move that DIV outside of the visible area?
Is it possible to do something after the dom is ready but it is not rendered(White screen)
I would like to hide the contents from user and after some operations i would like to show the final picture.
I could use "display:none" on my body tag but i am working on a huge project so i dont want to change every page.
Thanks
Here is how?
document.onload = function() {
//your codes
}
Unlike, window.onload this function runs after the DOM is loaded, so the manipulation is possible, but it does not require all the elements to be rendered.
Is it possible to do something after the dom is ready but it is not rendered
Browsers render the DOM incrementally as they parse the HTML into it. The state you describe will not happen naturally.
You can fake it such…
I could use "display:none" on my body tag but i am working on a huge project so i dont want to change every page.
If you don't want to change every page because it is too much work, then too bad. Go and set up an external stylesheet that every page uses.
If you don't want to change every page because you only want the changes to appear on certain pages, then use a more specific selector.
That said, preventing content from displaying and giving users a white screen (or even a loading screen) is just going to turn people off and drive lots of them to another site. I wouldn't recommend doing this.
if you could use JQuery this one is called when the dom is ready but the page not loaded
$(document).ready(function(){
)};
I'll contribute my own 2 cents here.
With jquery, the $("document").ready() event fires after the DOM has been fully loaded(without images, that is) to your browser, but not displayed. So I think to achieve what you want, you'll have to input some handler function inside the ".ready()" method to handle whatsoever you desire to achieve.
Is that what you were looking for?
If we call a javascript method myMethod() in a script tag which is before closing body, is it equivalent to calling myMethod() inside jQuery's document.ready function ? If not, Why ?
From here:
Under the hood: $(document).ready() As you would expect from John
Resig, jQuery’s method for determining when the DOM is ready uses an
assortment of optimizations. For example, if a browser supports the
DOMContentLoaded event (as many non-IE browsers do), then it will fire
on that event. However, IE can’t safely fire until the document’s
readyState reaches “complete”, which is typically later. If none of
those optimizations are available, window.onload will trigger the
event.
These events are independent of a location within the HTML tag, as other event still are going on even at the time of rendering </body>.
No it's not the same, you place the <script> tags before the closing </body> tag to avoid blocking the rendering of html on older browsers, AFAIK, but you have no guarantee that the DOM is "ready"
Not exactly. $(document).ready(); reacts on the so called DOMContentLoaded event which is fired right after the DOM has been loaded and the browser is aware of all the elements on the page (not the content itself).
The main reason why code is usually put inside these blocks is not that much related to preventing blocking of parallel loading but to ensure that the elements which are to be manipulated during page load are actually loaded and present in the DOM tree. Not much sense in manipulating elements which the browser is not aware of right?
Putting JavaScript content (or any other content for that matter) at the bottom of the page is actually more closely related to the onload event which is fired after the page has finished loading, including the content itself. Either way its almost certain that content inside $(document).ready() blocks will be executed before the one at the bottom of the page however if you load external libraries on which the code inside the ready() block relies you can't put those at the bottom of the page.
In general if you have code that isn't dependent on external libraries and a successful loading of DOM you can safely put it at the bottom of the page. If you however have stuff that needs to be executed right after the DOM has been loaded you most definitely want that code in the $(document).ready() block, but do have in mind that you can place that block wherever you want, even in the middle of the page (which can be a nice trick sometimes).
Twitter generates me box code to insert on page: http://pastebin.com/5TgkL5vP but on slow connection it prevent page from loading. Is there any way to add "Loading..." and make it async? (I know about iframe but its awful way)
There is a solution in here;
http://od-eon.com/blogs/stefan/asynchronous-loading-twitter-widgets/
$(window).load(function(){
$.getScript('http://widgets.twimg.com/j/2/widget.js', function(){
$.getScript('/media/js/twitter.js', function(){
$('#twtr-widget-1').appendTo('#twitter_p')
})
})
})
To delay the loading of the twitter widget you could load it after your whole page is loaded. You could use the window's onload event handler to start loading the twitter widget once your page has been downloaded.
Or you could use a javascript library (like jquery) to run that code once you HTML is loaded but images and CSS and other assets are still loading: jquery's .ready() method does just that.
In case you don't want to use bare javascript (although recommended for learning) jquery (like others) does provide a .load() event that behaves just like the onload example on W3c.
In any case, with any of those two methods you could place a "loading..." text in a placeholder and then replace it with the widget once it's loaded.
You should try experimenting with both and see which one produces the best perceived results. Sometimes you want the page's content to load blazingly fast, in that case you should hold all external content from being loaded until the content is loaded (using onload or .load()), while sometimes you want everything to be loaded more or less at the same time (using .ready()).
I hope it didn't come out backwards :D.
The solution explain by od-eon.com is OK but for IE the CSS is not correctly added because it tries to add CSS in a window onload event. This event is fired asynchronously so no CSS is added.
The line $('#twtr-widget-1').appendTo('#twitter_p') is not useful.
You must not add a CSS position attribute to the div which will contain the box because nothing is displayed in this case. If you want to add this box in an absolute div you must add an empty div in it and pass the div's id in parameter.