$(document).ready equivalant in JavaScript - javascript

I try to find equivalent code for jQuery $(document).ready, and find there are some different versions:
Version 1:
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
Version 2:
document.addEventListener('DOMContentLoaded', fn);
What is the difference? Why version 1 will check document.readyState? Also version 1 is a function, while version 2 is an executed statement. So should there be one statement for version 1:
ready(fn);

The documentation of jQuery has the answer to your question.
jQuery.ready():
Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.…
So your Version 2 has the described problem. While Version 1 calls the passed function even after the document is already ready.

The difference is that the first one will work even if the script is executed after DOMContentLoaded has fired (see document.readyState for more), provided you add the call to ready you asked about. The second won't, because the event is only fired once, so if the script is executed after that, fn will never get called.
So how could the script be executed after the event has already fired? Basically, if it's added dynamically, not as part of the document's initial HTML. Here are a couple of examples of how that could be:
A script element added after the document has loaded.
A module loaded via dynamic import() rather than static import.
There are probably others.
Also version 1 is a function, while version 2 is an executed statement. So should there be one statement for version 1:
ready(fn);
Yes, absolutely right.
I should note that you don't need either of those if you control how the script is included in the page. (So, you do need it in libraries, but rarely in apps/pages.) If you control how the script is included in the page, and want your code to run after the DOM has been built, here are several ways you can do that (IMHO, in order of best practice):
Use type="module" on the script to make it a module. Modules aren't executed until the DOM has been built (they're auto-deferred, even inline modules; see the next bullet point).
Use defer on your script tag (only works for src script tags referring to files, not inline scripts). Deferred scripts aren't executed until the DOM has been built.
Put the script tag at the end of the document, just before the closing </body> tag.
If you do any of those things, there's no need to use ready (jQuery's or the ones in your question).

Related

Whic spec define the ready event?

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

jQuery onLoad x jQuery onDomready

Every time I use jsFiddle I see two options to initialize the contents via jQuery: onLoad or onDomReady.
I Tested with most of the scripts I wrote and there was no functional difference. Searching on Google I saw that one of the main differences is that via onLoad, scripts will only start running after all the elements are loaded and that includes CSS external files, JS external files, images and etc., which can be useful if you need to load JS files in a certain order, but at any given moment one of these files makes reference to another who has not been loaded yet, while via onDomReady once the HTML page content is loaded, scripts begin to be loaded already without necessarily others have been.
Got this difference right? Is there any other differences to be studied and perceived?
Making comment as answer:
One major difference, jquery ready 'pseudo' event will be fired even handler
is set after DOM is effectively 'ready', jquery using internally a
promise. Window onload event won't be fired if handler is set after
window is loaded. e.g: http://jsfiddle.net/c58a6/
It should be then noted that there is no in-build equivalent of jQuery document ready event. For example, DOMContentLoaded in-build event won't be fired if settled after the DOM is ready.

Javascript and jQuery Execution/Sequence

A question/clarification regarding Javascript/jQuery execution and it's sequence.
Please excuse me if I seem to answer my own question here, but I feel I'm missing a key something in this process.
I was told my selectors weren't taking because the DOM wasn't ready which had brought this question. Script was initially in the head using the ready jQuery ready method.
Thanks everyone.
Problem:
No access to Drupal template files.
Can only add in the head.
Appending via jQuery isn't too useful with the script tag.
Our solution currently is linking to the file in the markup.
I'm really seeking clarification though to the process here.
Context:
(Sorry bout that)...
Element wasn't targeted by my selector, from the script in the head. Syntax was correct, as it targeted the HTML tag without issue.
My understanding was the ready method/resulting listener would trigger after the DOM was fully constructed.
What I believe I already know:
I know scripts should ideally be placed just above the closing body tag in the markup.
I know that when the tokenizer encounters a script tag, it stops everything and executes the script (unless defer/async).
I know this is why they should ideally be placed above the closing body tag so the DOM is ready.
I know that the jQuery ready method attaches a listener, when the browser is switched to it's ready state after the DOM has been loaded, it fires.
The Questions:
Given all of this, placement in the head renders the ready method useless as its being executed right away because of the tokenizer?
Is this really just to avoid colliding/overwriting multiple window.onloads? (Should've clarified.)
Given all of this, placement in the head renders the ready method useless as its being executed right away because of the tokenizer?
Wrong. The ready() method gets called only when the DOM has fully loaded, all ready() does is that it establishes a listener that waits for the DOM to load so that statements inside the ready() method get executed when the DOM is ready to be manipulated, in other words it adds a listener to the loaded event that gets called and executed only when the document has full loaded.
Is this really just to avoid colliding/overwriting multiple onloads?
What do you really mean by "colliding/overwriting" ? You can have several listeners listening to the same events in JavaScript, and they won't overwrite or collide with each other.
From your question:
I know that the jQuery ready method waits until the browser is switched to it's ready state after the DOM has been loaded.
Well, sort of. The jQuery ready method doesn't wait. It attaches an event listener. The function is attached, but not executed. The function is only executed when the DOM is ready; the rest of the page continues loading.
You're really in the sphere of micro-optimisation here. Yes, placing script elements at the end of the body is ideal, but it will make minimal difference in reality, unless you have a huge, complex and time-consuming script.

Is placing script tag before </body> tag equivalent to jQuery's document.ready method

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).

jQuery load external JavaScript with $(document).ready fails

I would like to load an external HTML. In addition, the external HTML contains some JavaScript code. Since the load function does not load this script, I have to use getScript:
<div id="external-content"></div>
<script type="text/javascript">
$("#external-content").load("external.html #myid", function() {
// do something
});
$.getScript("external.js");
</script>
That works like a charm unless the external.js has a $(document).ready command, which tries to access elements from external.html. It seems to me, that the event is fired too early. I also tried to put the command $.getScript("external.js"); into the .load callback, but did not succeed. Note that sing external.html separately and including the external.js directly works like expected.
Unfortunately, the timing of this makes sense (ie. this is correct behaviour). The script inside the tag fires up a retrieval of external.html and does not wait for it to return, it keeps moving on to the retrieval of external.js. In the meantime, the 'base' document is still loading and may (in fact probably) will complete before externa.html is retrieved.
So, you can run into a timing situation whereby:
Document is indeed ready (external.html being loaded is not a condition of the DOM being scriptable), external.js is loaded and available, but external.html hasn't been fully loaded yet. The document ready function will fire (because the document IS ready!) before the elements of external.html are present.
If you want to continue this approach, there are probably ways to rejig it such that you are using on() inside external.js to delegate to a listener to the base document (#myid) for events on elements inside external.html.

Categories