7

JavaScript Snippet – domReady() Function

 3 years ago
source link: https://cwestblog.com/2020/02/19/javascript-snippet-domready-function/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript Snippet – domReady() Function

Published by Chris West on February 19, 2020

Sometimes you may want to know if the DOM is ready to be manipulated. Most of the time you want to run some code only after the DOM is ready to be modified. For that reason for years we used jQuery’s ready() function or some equivalent. Now many have moved on and like to use plain old JavaScript to do everything without libraries. Still, a major benefit of using jQuery(…).ready() is that even if the document (or window‘s) DOMContentLoaded event already fired, the function passed will still be run.

The following will always print to the JS console even if the DOM was fully parsed long ago:

jQuery(function() {
console.log('The DOM is ready!');
});

On the other hand, the following will only print to the JS console if the DOM is not fully parsed at the time when the event listener is added:

addEventListener('DOMContentLoaded', function() {
console.log('The DOM is ready!');
});

A Simple Solution

The solution to this problem is to test to see if the DOMContentLoaded event would have possibly fired already and then call the function immediately. With this in mind you could use the following code to essentially do the same thing that jQuery does but without needing jQuery:

/** * Determines if the document has finished loading and has been parsed. * @param {Function|undefined} opt_callback * Optional. If given as a function it will be called once the DOM is * ready. The first parameter passed to it will be the event object in the * case that the callback is delayed, otherwise it will be null. The "this" * keyword will refer to the document. * @param {HTMLDocument|undefined} opt_document * Optional. Defaults to the current document. If given as a document this * will be the document tested against. * @returns {boolean} * Value indicating if the document is finished loading and has been parsed. * @license Copyright 2020 - Chris West - MIT Licensed */ function domReady(opt_callback, opt_document) { var doc = opt_document || document; var isReady = /^(loaded|complete|interactive)$/.test(doc.readyState); if (opt_callback) { if (isReady) { opt_callback.call(doc); } else { // https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event#Browser_compatibility doc.addEventListener('DOMContentLoaded', function() { opt_callback.apply(doc, arguments); }, false); } } return isReady; }

Here is an example showing how to use this function:

domReady(function() {
console.log('The DOM is ready!');
});

If you just want to determine if the DOM is currently ready you can also call it this way:

if (domReady()) {
console.log('The DOM is ready!');
}
else {
console.log('The DOM is not ready yet.');
}

You can even determine if the code is being called right away from within the function call by doing something like this:

domReady(function(event) {
console.log('This is ' + (event ? 'a delayed' : 'an immediate') + ' call.');
});

Legacy Solution

If you would like to use this domReady() function but you need to support legacy browsers such as IE8 or lower then you can use the following definition:

/** * Determines if the document has finished loading and has been parsed. * @param {Function|undefined} opt_callback * Optional. If given as a function it will be called once the DOM is * ready. The first parameter passed to it will be the event object in the * case that the callback is delayed, otherwise it will be null. The "this" * keyword will refer to the document. * @param {HTMLDocument|undefined} opt_document * Optional. Defaults to the current document. If given as a document this * will be the document tested against. * @returns {boolean} * Value indicating if the document is finished loading and has been parsed. * @license Copyright 2020 - Chris West - MIT Licensed */ function domReady(opt_callback, opt_document) { var doc = opt_document || document; var RGX_IS_READY = /^(loaded|complete|interactive)$/; var isReady = RGX_IS_READY.test(doc.readyState); if (opt_callback) { if (isReady) { opt_callback.call(doc); } else { // https://developer.mozilla.org/en-US/docs/Web/API/Document/readystatechange_event#Browser_compatibility var hasListener = !!doc.addEventListener; doc[hasListener ? 'addEventListener' : 'attachEvent']( (hasListener ? '' : 'on') + 'readystatechange', function () { if (!isReady && RGX_IS_READY.test(doc.readyState)) { isReady = true; opt_callback.apply(doc, arguments); } }, hasListener && undefined // evaluates to false or undefined ); } } return isReady; }

The function is called the same way. The main differences are that if document.addEventListener() doesn’t exist document.attachEvent() is used and the readystatechange event is being targeted instead of the DOMContentLoaded event.

Final Words

Honestly, there are still other reasons why you may decide to use libraries such as jQuery which already provide this functionality. On the other hand, feel free to use this function if you want to minimize your code base. As always, happy coding! 😎


Leave a Reply Cancel reply

placeholder.jpg
Name *
Email *
Website

Save my name, email, and website in this browser for the next time I comment.

 −  three  =  1

What's on your mind?

Recommend

  • 67

    This plugin is still in alpha stage, so it might be unstable. Feel free to share your feedback and report issues! This plugin is in JetBrains Plugins Repository! Get it from

  • 152

    README.md Neosnippet The Neosnippet plug-In adds snippet support to Vim. Snippets are small templates for commonly used code that you can fill in on th...

  • 87

    While coding for our current project, I had the following thought: "Is it possible somehow not to write the variable of the collection every time I want to add some elements to it?" So I searched if there is a way to do that and found out a s...

  • 29
    • cwestblog.com 4 years ago
    • Cache

    Raw JavaScript - domReady() Function

    Sometimes you may want to know if the DOM is ready to be manipulated. Most of the time you want to run some code only after the DOM is ready to be modified. For that reason for years we used

  • 7

    On a rare occasion you may need to convert a column name from Excel or Google Sheets to a number. For example you may be seeing references to a random column such as D, G, BV, etc. but you don’t know how to represent it as a number. Instead...

  • 5

    总所周知,写文章需要一个标题。虽然我们搞代码的人一般都喜欢单刀直入,但是受制于文体的约束和发表载体的要求,有时不得不想一个标题。而起一个标题,不亚于起一个

  • 5

    总所周知,写文章需要一个标题。虽然我们搞代码的人一般都喜欢单刀直入,但是受制于文体的约束和发表载体的要求,有时不得不想一个标题。而起一个标题,不亚于起一个函数名或者变量名。单就这篇文章,我就有好几个草稿标题,例如:《页面加载指标演进之路》,《...

  • 4
    • cwestblog.com 2 years ago
    • Cache

    JavaScript Snippet – parseJSONC()

    JavaScript Snippet – parseJSONC() – Chris West's Blog Last year I needed a way to be able to parse JSON with comments (also known as JSONC). With that in mind I wrote the following short solution which will essentially remove JavaScrip...

  • 7

    Your next Add-to-Calendar Button A convenient JavaScript snippet, which lets you create beautiful buttons, where people can add events to their calendars. Use case // Who this is for This is for everybody, wh...

  • 5
    • cwestblog.com 2 years ago
    • Cache

    JavaScript Snippet – importUnpkg()

    JavaScript Snippet – importUnpkg() – Chris West's Blog There are many websites that make it super easy to import node packages into your website. One of them is Unpkg.com. If...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK