I've been developing in javascript for a few months and I have been using $(document).ready(function(){ at the beginning of all my scripts. I've noticed other folks don't use this in their scripts but I can't seem to get mine working without it. I'd like to keep my code cleaner, but for all my google searches I can't seem to figure out how to get rid of it.
I know it tells the browser to execute my script as soon as the page loads but is there something global I can set so that I don't need to explicitly tell the browser to execute each of my scripts when the page loads? Or is it a more global problem with where in my html files the scripts are located?
You're needing document.ready probably because you're interacting with the DOM before it loads. How can the script manipulate elements that are not there yet?
If you stick your script at the end of the file you will not need it. It's also good practice to do so for a lot of Javascript files as they can take time to process (especially if they're hosted externally). Putting them at the end of the file often speeds up the page load time.
All $(document).ready(function() { ... }); or $(function() { ... }); does is wait for the document to be ready for manipulation. You should use $(document).ready(function() { ... }); or $(function() { ... }); if your scripts are inline or in the <head /> section because JavaScript executes in the order in which it appears on the page otherwise.
To do away with $(document).ready(function() { ... }); or $(function() { ... });, simply move your scripts down to the bottom of the page after all of your content, right before the closing </body> tag.
Putting the scripts at the bottom is really a best practice anyway. For this and other best practices, I recommend you take a look at Html5Boilerplate and Yahoo! Best Practices.
the $(document).ready() convention is part of jQuery, not just JavaScript. From their' documentation on the ready function:
This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
So yes, it is required. jQuery does come with a shorthand for this though, so you could do the following:
$(function() {
//jquery code
};
Related
This question already has answers here:
document.ready inside body tag
(2 answers)
Closed 9 years ago.
We often read here and there, that we must place our js code either on the page head section or before (sorry) the end body tag. Discussions about this aside, I'm just looking to know what are the reading order for such things by the browsers (taking that they do act as equals here):
Can we place:
$(document).ready(function(){
No matter where on the page structure, because we are using $(document).ready or should we still place it on the head section ?
Can anyone please clarify this.
If my question isn't clear, I can rephrase.
You can place a script anywhere in the document. Best practice usually advises placing scripts in the footer for page load performance concerns. Further, best practice usually advises placing the scripts together for ease of maintenance.
However, per the spec, there is no restriction on where in the document you place a script tag. You may place them together in the header, at the bottom of the body, sprinkled all over the document, or any combination thereof.
The use of the jQuery construct $(document).ready has the same result regardless of where it is placed within the document. The key is to understand the functionality behind this construct:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.
So, ready is similar to document.onload, but not the same. It doesn't matter where the code is, if you execute it when document.onload is fired or when jQuery fires ready. Code's placement in a document is only significant if it is NOT wrapped by some event handler/listener.
The only restriction on the location on $(document).ready is that it cannot happen before you include the jQuery library. $(document).ready is using jQuery, so if jQuery doesn't exist.... you can't use it.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</head>
<body onload="alert('executed on document.onload event');">
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</body>
</html>
Documentation
SCRIPT specification at W3 - http://www.w3.org/TR/html401/interact/scripts.html
script (html 5) specification at W3 - http://www.w3.org/TR/html-markup/script.html
Placing Javascript in your pages at quirksmode - http://www.quirksmode.org/js/placejs.html
Jquery ready - http://api.jquery.com/ready/
AFAIK, $(document).ready event gets raised after DOM is completely loaded so it doesn't matter where you place it.
But they say to write the script at end of the body because page will show up to the end user instantly and javascript will continue to run as background process.
The browser executes the script from the top to the bottom, so the srcipt in the head section will execute before the script in the body. I prefer to put the script undernith the html code, but generally it desn't matter much if you vait for the page to fuly load.
The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them. But since you're waiting for the DOM to load anyway, it doesn't matter.
If you have a small function, then I would just put the document ready function in the head tags.
As far as i know, the BKM is to place it in the footer (although mostly developers tend to place it in the head tag).
Main reason - most of the document DOM is rendered to the browser prior to loading JS.
I'm experiencing an issue (which I still need to fix) where my entire page does not load. It gets cut off in the middle of an element.
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
I was thinking of just putting <div id="end_of_page"></div> at the bottom of the page, and checking if that was rendered, if not, i'll know something went wrong and can reload to try again.
thanks!!
Is there a way using jquery or javscript to do something like:
if (some element has not loaded yet) {refresh the page}
You can do that, yes. Put this in the head after including jQuery:
<script>
jQuery(function($) {
if (!$("#end_of_page")[0]) {
// Something went wrong, load again
location.reload();
}
});
</script>
You'll enter the body of the loop (and so, force a reload) if the end_of_page element doesn't exist as of when the jQuery ready event fires (which is meant to be when the page is done loading).
But: Better by far to figure out why your page is getting cut off half-way through and solve that. This sort of workaround is not a solution.
You can use
$(document).ready(function(){
// code here
});
that code will only run when the page has loaded. A convenient shorthand is:
$(function(){
// code here
});
assuming your jQuery object is $. To finish your requirement, you can have a variable that is set within the load function, then use a timer set at the start of the page to check for it. If it's not there, reload.
Personally, I think you should invest some time into figuring out why your pages only half-way (Firebug or the Chrome Inspector may help you do this, it might be a resource in your page that is causing it to hang, and since most HTTP requests are only made 2 at a time per hostname, it might be waiting for that to return before fetching the rest).
Might be a server-side issue OR some script or library is stealing your fish $ (AKA: 'Dollar').
I'll rather suggest you to debug your code instead of refreshing the page trying to fix issues.
Make sure your scripts are in the head of your document, and jQuery + your jQ functions right before the closing </body> tag wrapped in:
(function($){ /*your functions*/ })(jQuery);
This question is just to clear some things up. Some things like this have been asked before, and this rounds them all up into one question - where should JavaScript go in the HTML document, or, more importantly, does it matter? So, one of the things I'm asking is, does
<head>
<script type="text/javascript">
alert("Hello world!");
</script>
</head>
at all differ (in terms of functionality) from
<body>
<!-- Code goes here -->
<script type="text/javascript">
alert("Hello world!");
</script>
</body>
More importantly, I want to focus on JS that modifies or uses elements from the DOM in any way. So I know that if you put something like document.getElementById("test").innerHTML = "Hello world!" before <element id="test"></element> in your body, then it won't work since the body is loaded from top to bottom, making the JS load first, which will then proceed to try to manipulate an element that doesn't exist yet. So it should, just like the above, either go in the <head> or just before the </body> tag. The question is, aside from organisation and sorting, does it matter which one of these is chosen, and if so, in what way?
Of course, there is also a third method - the jQuery way:
$(document).ready(function(){ /*Code goes here*/ });
That way, it doesn't matter where in the body you place the code, since it will only be executed when everything has loaded. The question here is, is it worth importing a huge JS library just to use a method the need for which could be replaced with an accurate placing of your scripts? I'd just like to clear things up a little here, if you would like to answer, go ahead! Summary: where should different kinds of scripts go - head or body, and/or does it matter? Is jQuery worth it just for the ready event?
Most recommended method is to put it before </body> tag. Yahoo performance article also suggests that other than YSlow and Page Speed addons by Yahoo and Google respectively.
Quoting from Yahoo article linked above:
The problem caused by scripts is that they block parallel downloads.
The HTTP/1.1 specification suggests that browsers download no more
than two components in parallel per hostname. If you serve your images
from multiple hostnames, you can get more than two downloads to occur
in parallel. While a script is downloading, however, the browser won't
start any other downloads, even on different hostnames.
When you put scripts in <head> tag, the browsers goes for them thereby keeping other stuff on hold until scripts are loaded which users will perceive like slow loading of the page. This is why you should put scripts at the bottom.
As for:
$(document).ready(function(){/*Code goes here*/});
It is fired when DOM is available and ready to be manipulated. If you put your code at the end, you won't necessarily need this but usually this is needed because you want to do something as soon as DOM is available for use.
Although common practice, putting script tags in the head is not usually a good idea, as it holds up the rendering of your page until those scripts have been downloaded and processed (barring your use of async or defer and the browser supporting them).
The usual recommendation is to put script tags at the very end of the body tag, e.g., just before </body>. That way, all of the DOM elements above the script will be accessible (see links below). One caveat on that is that there can be a brief moment when your page has been at least partially-rendered but your scripts not processed (yet), and if the user starts interacting with the page, they may do something to raise an event that your script hasn't had time to hook yet. So you need to be aware of that. This is one reason for progressive enhancement, which is the idea that the page will work without JavaScript, but work better with it. If you're doing a page/app that just won't work without JavaScript at all, you might include some inline script at the top of the body tag (e.g., <script>minimal code here</script>) that hooks any bubbling events on document.body and either queues them for action when your script is loaded, or just asks the user to wait.
Using features like jQuery's ready is fine, but not really necessary outside of libraries (e.g., if you're in control of where the script tags will be, you don't usually need to use it; but if you're writing a jQuery plug-in that needs to do something on load [which is relatively rare, normally they just wait to be called], you usually do).
More reading:
YUI Best Practices for Speeding Up your Website
Google on when the DOM will be ready
It is possible to download javascripts in parallel by doing something like this:
(function () {
var ele = document.createElement('script');
ele.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
ele.id = "JQuery";
ele.onload = function () {
//code to be executed when the document has been loaded
};
document.getElementsByTagName('head')[0].appendChild(ele);
})();
In the example it downloads minified JQuery v1.7.2 from Google, this is a good way to download JQuery since downloading it from Google is like using a CDN and if the user has been on a page that used the same file it might be cached and therefor doesn't need to be downloaded
There is a really good Google tech talk about this here http://www.youtube.com/watch?v=52gL93S3usU&feature=plcp
I have an external javascript that contains something like:
document.writeln("<script type='text/javascript' src='...'></script>");
In the original html i have something link
<div id="banner">
<script type="text/javscript" src="<the external javascript above>"></script>
</div>
How can i load that delayed?
I've tried using window.setTimeout and append that javascript but its not working.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
Thank you.
You can call your injection code on window.onload.
window.onload = function() {
inject();
doSomethingElse();
};
window.onload will wait until all assets have finished downloading, such as images and scripts. After scripts are downloaded, you can inject your code to page.
Maybe a better way to do it would be to add a delay to the script.
Also, if you use something other than 'document.writeln' for example:
$('#banner').append(...);
you can better direct where it goes.
There is an open source javascript library for doing this kind of thing: http://labjs.com/
I have used it in the past and it worked very well.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
That is not entirely true. Especially if the div is empty you could simply use: document.getElementById('banner').innerHTML = "<h1>HTML-Output here.</h1>"
Bukko's answer would work as well if you are using jQuery. My answer is pure Javascript. With this newfound freedom you should be able to simply put the loading of your script at the bottom of the page or use a custom body.onload() function
Edit: or simply follow Samet's suggestions in conjunction with the .innerHTML. Hope this helps.
i am building a website using asp.net mvc and jquery.
as a best practice its known that including javascript should be done at the end of the html page.
so i basically include jquery.js and other js files in the end of the html before the /body tag.
now i have some controls which are included in the page as partials. and they need to add functionally to $(document).ready.
but i write the code as a script tag in the partial then the jquery library wont be even included at that time and i cant include this javascript at the end of the html from within the partial. since the partial is included in the middle of the html.
Move all javascript in single file(you may exclude jQuery file) and move it to the bottom.
If you are talking of good practice then, then writing inline javascript is not a good practice too.
So I would suggest move all your java script to single file,there are many tools available that merge multiple javascript files and crunch them, use those!!
Edit1
You may try this:
//define this at before body (or at the beginning of body)
var arrReadyCollection = [];
Inside controllers:
arrReadyCollection.push(site.module.Dialog_AcceptChanges);
arrReadyCollection.push(some_thing_Else);
At the end, after jQuery file
for (i=0;i<arrReadyCollection.length; i++)
{
var fn= arrReadyCollection[i];
$(document).ready(fn);
}
Note: this is not recommended way, its just way you can solve your problem
You should use a javascript loader like LABjs.
You can use it to run javascript when certain libraries are loaded and run.
<head>
<script src="lab.js"></script>
</head>
<body>
<script>
// $LAB uses async loading, no need to deferr to the end of body
// keeping a reference to the $LAB deferred is important, so we can
// use it from within partials (see below)
myPage.$LAB = $LAB
.script('someScript.js')
.script('someOtherScript.js')
.wait(function () {
// your scripts are loaded!
});
</script>
</body>
In your partials you can hook into LABjs, eg like this:
<script>
myPage.$LAB.script('jQuery.js').wait(function () {
// jQuery was loaded!
// if jQuery was loaded already by another partial or your main layout
// it will not be loaded again, but the callback will fire immediately!
});
</script>
That beeing said you really should follow the advice given by Praveen and tie your javascript files up as much as possible. Each request to your server will cost time and decrease the responsivness of your website.
Either fix your "control" files so that they don't require inline JavaScript, or else include jQuery at the top of the file.
You could also write a small "$" function of your own that you'd include before jQuery (and at the top). However, you'd be better off fixing those controls anyway.
Another possible solution would be to add a script tag dynamically from within the partial. This however could get messy if you want to run more than a few lines of code, eg:
<script>
var script = docuement.createElement('script');
script.innerHTML = "$(document).ready(function () { doSomething(); });";
document.body.appendChild(script);
</script>
This should run after the jQuery (which should be already somewhere at the end of the body) was loaded and run.
UPDATE:
This does not work, I assumed that inserting script elements in a DOM that wasn't ready yet wouldn't execute before the DOM is ready.
Use CDN's and quit obsessing about doubtful optimization. From the excellent jQuery in Action book, sec 1.22
NOTE For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.