Jquery: Why Use Document.Ready If External Js At Bottom of Page

jQuery: Why use document.ready if external JS at bottom of page?

Great question.

There is some confusion around the whole "put scripts at the bottom of your page" advice and what problem(s) it attempts to solve. For this question I am not going to talk about whether putting scripts at the bottom of the page affects performance/loadtimes or not. I am only going to talk about whether you need $(document).ready if you also put scripts at the bottom of the page.

I'm assuming you are referencing the DOM in those functions you are immediately invoking in your scripts (anything as simple as document or document.getElementById). I'm also assuming you are asking only about these [DOM-referencing] files. IOW, library scripts or scripts that your DOM-referencing code requires (like jQuery) need to be placed earlier in the page.

To answer your question: if you include your DOM-referencing scripts at the bottom of the page, No, you do not need $(document).ready.

Explanation: without the aid of "onload"-related implementations like $(document).ready the rule of thumb is: any code that interacts with DOM elements within the page should to be placed/included further down the page than the elements it references. The easiest thing to do is to place that code before the closing </body>. See here and here. It also works around IE's dreaded "Operation aborted" error.

Having said that, this by no means invalidates the use of $(document).ready. Referencing an object before it has been loaded is [one of] the most common mistakes made when beginning in DOM JavaScript (witnessed it too many times to count). It is jQuery's solution to the problem, and it doesn't require you to have to think about where this script will be included relative to the DOM elements it references. This is a huge win for developers. It's just one less thing they have to think about.

Also, it's often difficult or impractical to move all DOM-referencing scripts to the bottom of the page (for example any script that issues document.write calls have to stay put). Other times, you are using a framework that renders some template or creates pieces of dynamic javascript, within which references functions that need to be included before the js.

Finally, it used to be "best practice" to jam all DOM-referencing code into window.onload, however it has been eclipsed by $(document).ready implementations for well document reasons.

All this adds up to $(document).ready as a far superior, practical and general solution to the problem of referencing DOM elements too early.

Is $(document).ready necessary if I put all my JavaScript at the bottom of the page?

This SO answer says NO:

stackoveflow question

$(document).ready is for assurance full DOM is available at the time the function is called.
Any functions and events not depending on the DOM don't need to be put into the ready event.

Also - to improve page rendering speed - load javascript files dynamically in non-blocking fashion: http://berklee.github.com/nbl/ or https://github.com/rgrove/lazyload/

This technique works somewhat like this:

 var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

This new element loads the source file file1.js. The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated. You can even place this code in the header of a document without affecting the rest of the page (aside from the one HTTP connection that is used to download the file).

this book: "High Performance JavaScript" by Nickolas Zakas has a lot of interesting information about JavaScript performace optimization.

Call an external js script after document ready

You're looking for $.getScript(url), which does exactly that.

when do you need to use $(document).ready()?

In the case of external scripts $(document).ready() could be the only option. As for inline script it is a little different.

According to HTML 4.01 standard it seems a little ambiguous whether or not the initialization technique shown above is legal:

http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.4

Scripts that are executed when a document is loaded may be able to
modify the document's contents
dynamically. The ability to do so
depends on the scripting language
itself (e.g., the "document.write"
statement in the HTML object model
supported by some vendors).

HTML documents are constrained to conform to the HTML DTD both before
and after processing any SCRIPT
elements.

In the HTML 5 draft it seems very clear that this practice is fully supported:

http://www.w3.org/TR/html5/scripting-1.html#scripting-1

The following sample shows how a
script element can be used to define a
function that is then used by other
parts of the document. It also shows
how a script element can be used to
invoke script while the document is
being parsed, in this case to
initialize the form's output.

<script>
function calculate(form) {
var price = 52000;
if (form.elements.brakes.checked)
price += 1000;
if (form.elements.radio.checked)
price += 2500;
if (form.elements.turbo.checked)
price += 5000;
if (form.elements.sticker.checked)
price += 250;
form.elements.result.value = price;
}
</script>
<form name="pricecalc" onsubmit="return false">
<fieldset>
<legend>Work out the price of your car</legend>
<p>Base cost: £52000.</p>
<p>Select additional options:</p>
<ul onchange="calculate(form)">
<li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
<li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
<li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
<li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
</ul>
<p>Total: £<output name=result></output></p>
</fieldset>
<script>
calculate(document.forms.pricecalc);
</script>
</form>

execute code in $(document).ready() in external javascript file multiple times with different variable values

You are attempting an ugly side-effect hack using a global variable. Please, please fix your code to be a function that accepts an argument that you can just call twice with different arguments when the document is ready.

Thanks, that is exactly what I needed. Now my code looks like this:

external_script.js:

function do_stuff( local_var ) {
alert( local_var );
}

index.html:

<script src="external_script.js"></script>
<script>
$(document).ready(function(){
do_stuff( "foo" );
do_stuff( "bar" );
});
</script>

Why does jQuery sometimes need $(document).ready?

If all jQuery code would run when the document is ready, it would have to queue up all calls until then. That would make every call before the ready event asynchronous, which would make everything more complicated.

Example:

var prefix = "A:";
$('.colA').text(function(i, t){ return prefix + t; });
prefix = "B:";
$('.colB').text(function(i, t){ return prefix + t; });

This will add the prefix A: to the text of the elements with class="colA" and B: to the text of the elements with class="colB".

If the calls were asynchonous, it would add B: to all the elements, because both assignments would run before any of the jQuery code.

Should we wrap jquery code $(document).ready(function(){ in external js also

Placing your code in -

$(document).ready(function(){
// Your code here
});

is not explicitly required. It's simply an easy way of ensuring your javascript will run after the DOM has fully loaded. (Note that it does not wait for images to fully load.)

If your file is being loaded at the bottom of the page, you may be able to get away with not using it. But if you just want a safe and easy way to make sure the DOM is finished loading, then use it.

This answer...

jQuery: Why use document.ready if external JS at bottom of page?

gives a nice explanation.

Load external script after page is done loading by using $(document).ready() and $.getScript()

As per the MDN documentation:

If a script element has a src attribute specified, it should not have a script embedded inside its tags.

So move the code to a separate script tag.

<script src="js/jquery-3.3.1.js"></script> 
<script>
$(document).ready( function () { $.getScript("./js/script.js"); } );
</script>


Related Topics



Leave a reply



Submit