Javascript when document ready

How to check if document is ready using JavaScript

To check if the document is ready and run some code, you can add an event handler to the DOMContentLoaded event of the document object.

The DOMContentLoaded event is fired when the initial HTML document has been fully loaded and parsed without waiting for stylesheets, images, and subframes to finish loading.

// Define event handler const handler = e =>  console.log(`Document is ready!`) > // Listen for `DOMContentLoaded` event document.addEventListener('DOMContentLoaded', handler) 

If you are not interested in reusing the event handler function, replace it with an anonymous function as shown below:

// Listen for `DOMContentLoaded` event document.addEventListener('DOMContentLoaded', e =>  console.log(`Document is ready!`) >) 

The DOMContentLoaded event works in all modern browsers, including IE9 and above.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

$( document ).ready()

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 ).on( «load», function() < . >) will run once the entire page (images or iframes), not just the DOM, is ready.

// A $( document ).ready() block.
$( document ).ready(function( )
console.log( "ready!" );
>);

Experienced developers sometimes use the shorthand $() for $( document ).ready() . If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form.

// Shorthand for $( document ).ready()
$(function( )
console.log( "ready!" );
>);

You can also pass a named function to $( document ).ready() instead of passing an anonymous function.

// Passing a named function instead of an anonymous function.
function readyFn( jQuery )
// Code to run when the document is ready.
>
$( document ).ready( readyFn );
// or:
$( window ).on( "load", readyFn );

The example below shows $( document ).ready() and $( window ).on( "load" ) in action. The code tries to load a website URL in an and checks for both events:

html>
head>
script src="https://code.jquery.com/jquery-1.9.1.min.js"> script>
script>
$( document ).ready(function( )
console.log( "document loaded" );
>);
$( window ).on( "load", function( )
console.log( "window loaded" );
>);
script>
head>
body>
iframe src="http://techcrunch.com"> iframe>
body>
html>

Last Updated

Suggestions, Problems, Feedback?

Chapters

Books

Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

Источник

JavaScript document.ready() – Document Ready JS and jQuery Example

Ihechikara Vincent Abba

Ihechikara Vincent Abba

JavaScript document.ready() – Document Ready JS and jQuery Example

When working with JavaScript and the Document Object Model (DOM), you might want your script to run only when the DOM has loaded.

You can do this using the $(document).ready() method in jQuery, or the DOMContentLoaded event in vanilla JavaScript.

In this article, you'll learn how to make your JavaScript code run only when the DOM has loaded using jQuery and vanilla JavaScript.

How to Use the $(document).ready() Method in jQuery

Before JavaScript runs in the browser, it waits for the contents of the document to load. This includes stylesheets, images, and so on.

As a convention, placing the script element just before the closing body tag makes the script wait for the rest of the document to load before running.

We also can make this process faster in jQuery by using the $(document).ready() method. The $(document).ready() method only waits for the DOM to load, it doesn't wait for stylesheets, images, and iframes.

In the code above, the $(document).ready() method will only run after the DOM has loaded. So you'll only see "Hello World!" in the console after the $(document).ready() method has started running.

In summary, you can write all your jQuery code inside the $(document).ready() method. This way, your code will wait for the DOM to be loaded before running.

How to Use the DOMContentLoaded Event in JavaScript

Just like jQuery's $(document).ready() method, the DOMContentLoaded event fires once the DOM has loaded – it doesn't wait for stylesheets and images.

Here's how to use the DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", () => < console.log("Hello World!"); >);

Once the DOM has loaded, the DOMContentLoaded event will detect it and run.

You should use the DOMContentLoaded event when:

  • You have certain functionalities in your webpage that should fire immediately without waiting for the rest of the page content.
  • You have a script tag placed within the head element.

Summary

In this article, we talked about the $(document).ready() method in jQuery, and the DOMContentLoaded event in vanilla JavaScript.

We use them to execute JavaScript code when the DOM has loaded.

The interesting part of these functionalities is that they let JavaScript code run without waiting for images and stylesheets to load completely in a web page.

Источник

Replace the jQuery Document Ready Function with JavaScript

The jQuery document ready ( $(document).ready() ) method was implemented to execute code when the DOM is fully loaded. Since it executes the given function when all DOM elements are available, you can be sure that trying to access or manipulate elements will work.

Before jQuery 3.0, the typical usage with a anonymous function looked like this:

$(document).ready(function()  // Handler for .ready() called. >); 

jQuery 3.0 ready() Changes

Before the release of version 3, there were several ways you could call the ready method:

  • on the document element: $(document).ready(handler);
  • on an empty element: $().ready(handler);
  • or directly (i.e. not on a specific element): $(handler);

All above named variants are functionally equivalent. The specified handler will be called when the DOM is fully loaded, no matter on which element it was called. In other words, calling it on an image element $("img") versus the document element doesn’t indicate that the callback is fired when the specified element is loaded. Instead, it will be called when the entire DOM is fully loaded.

In jQuery 3.0, all other syntax methods except $(handler); are deprecated. The official justification is:

This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method’s behavior.

Difference Between the Ready and Load Events

The ready event is fired when the DOM is fully loaded and accesses to elements are safe. The load event, on the other hand, is fired after the DOM and all assets have loaded.

The load event can be used as follows:

$(window).on("load", function() // Handler when all assets (including images) are loaded >); 

This waits not only for the DOM to be ready for interaction but also for images to be completely loaded (which can take time, depending on the image sizes).

For normal DOM manipulations you’ll probably not need the load event, But it might be the right choice if you’d like to show a loading spinner until all assets are loaded, for example, or if you’d like to do some calculations with image sizes.

You Probably Don’t Need jQuery.ready()

The ready method makes sure that code is only executed when all DOM elements are safe to be manipulated. But what does this mean? When you’re executing JavaScript code inside the section of an HTML document then this would make sure that the code is executed when the browser has loaded all following elements (e.g. the element) too:

doctype html> html> head> meta charset="utf-8"> title>.ready() tutorialtitle> script src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"> script> script> $(function() // .ready() callback, is only executed when the DOM is fully loaded var length = $("p").length; // The following will log 1 to the console, as the paragraph exists. // This is the evidence that this method is only called when the // DOM is fully loaded console.log(length); >); script> head> body> p>I'm the content of this websitep> body> html> 

If you’re executing JavaScript as the last thing inside the , you probably don’t need to wrap it inside ready() , as all elements you might try to manipulate or access are already loaded:

doctype html> html> head> meta charset="utf-8"> title>.ready() tutorialtitle> head> body> p>I'm the content of this websitep> script src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"> script> script> var length = $("p").length; // The following will log 1 to the console, as the paragraph exists. console.log(length); script> body> html> 

Plain JavaScript ready() Alternative

For modern browsers, and IE9+, you can listen for the DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function() // Handler when the DOM is fully loaded >); 

But, note that the callback will not be executed if the event has already fired. To make sure the callback is always run, jQuery checks the readyState of a document (reference) and, if it’s already complete , executes the callback immediately:

var callback = function() // Handler when the DOM is fully loaded >; if ( document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll) )  callback(); > else  document.addEventListener("DOMContentLoaded", callback); > 

You could also include the domReady library, which has already implemented this solution.

Older versions of Internet Explorer

For IE versions less than or equal 8, you could use the onreadystatechange event to detect the readyState of a document:

document.attachEvent("onreadystatechange", function() // check if the DOM is fully loaded if(document.readyState === "complete") // remove the listener, to make sure it isn't fired in future document.detachEvent("onreadystatechange", arguments.callee); // The actual handler. > >); 

Alternatively you could use the load event, like jQuery does, as this will work in any browser. This also results in a time delay, as it’ll wait for all assets to be loaded. Note that you’ll also have to check the readyState in this solution, like explained above, to make sure the callback will still be executed even if the event has already fired.

Conclusion

If you’re searching for a plain JavaScript alternative for the ready method you can proceed with the DOMContentLoaded event. If your system requirements include IE < 9 you can use the onreadystatechange event.

If you’re using jQuery in your project you can safely proceed with using the jQuery document ready function, but remember to avoid using the (deprecated) ready() method on elements (e.g. $(document).ready() ) as mentioned earlier.

And lastly, don’t forget that in many situations you may not need any of these solutions — just move your JavaScript before the closing tag and you can be sure that the DOM has finished loading!

Share This Article

Julian is a passionate software developer currently focusing on frontend technologies and loves open source.

Источник

Читайте также:  Php выполнение post запроса
Оцените статью