Find a more complete cheat-sheet here
Javascript has a couple of alternatives to jQuery's $(document).ready()
function, which is used to detect when the DOM has loaded and is ready to be manipulated. A typical jQuery example would look something like this:
// wait until DOM has loaded before running code
$(document).ready(function() {
// this code is only run once the DOM has loaded
$('a').click(function(e) {
e.preventDefault();
console.log($(this).attr('href'));
});
});
This example binds a click on all links, prevents the link from visiting the page and logs the destination to the console. The $(document).ready()
line is important to ensure that the links exist on the page before we try to bind the click event - if the script ran before the DOM was ready then our click function wouldn’t be bound, so links would behave normally.
So, to replicate the $(document).ready()
function in plain Javascript (i.e. not using jQuery), you can use one of the following.
DOMContentLoaded
DOMContentLoaded is an event fired when the DOM has finished loading, but doesn't wait for stylesheets or images to load. In this respect, it's functionally identical to jQuery's $(document).ready()
event: as soon as the DOM is ready for manipulation, the event fires. Example usage:
// listen for the DOMContentLoaded event, then bind our function
document.addEventListener('DOMContentLoaded', function() {
// this is a workaround - querySelectorAll returns a non-iterable NodeList instead of an array
// so take Array.forEach() and pass the NodeList into it so we can iterate!
[].forEach.call(document.querySelectorAll('a'), function(el) {
// add the click handler to each link
el.addEventListener('click', function(e) {
e.preventDefault();
// log the href attribute
console.log(el.getAttribute('href');
});
});
document.readyState
document.readyState is a flag with several different values, rather than an event like DOMContentLoaded
. Accordion to MDN, it can have a value of 'loading' while the page is still loading, 'interactive' once the DOM is ready but resources such as images and stylesheets are still being downloaded, and 'complete' when everything has finished loading (equivalent to $(window).load()
). There is an event called readystatechange
associated with this flag which is fired when the value of document.readyState changes. As such, it can be used as an alternative to $(document).ready()
or DOMContentLoaded
:
// listen for changes to document.readyState - onreadystatechange is
// fired when readyState value is changed
document.onreadystatechange = function () {
// check the value - if it's 'interactive' then the DOM has loaded
if (document.readyState === "interactive") {
// add code here
}
}