Step 3: DOM Ready
The DOM Ready function takes a function as a callback parameter. When the DOM is ready this callback function will be called.
This is one of the most important method on your library. Any DOM manipulation code like getting element attributes, setting attributes, changing css etc can only be done once the DOM is ready to be manipulated.
There can be multiple DOM ready function and each function will be executed on FIFO basis.
Syntax
var string = document.readyState;
The readyState of a document can be one of following:
- loading – The document is still loading.
- interactive – The document has finished loading and the document has been parsed but sub-resources such as images, style sheets and frames are still loading.
- complete – The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.
TIP : The array shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
Let’s take a look at the code.
Step 1 – Check if the selector is a function
We check if the type of selector is function we pass the control to an internal helper function called handleDOMReady(selector).
Step 2 – handleDOMReady function
If the DOM is already ready (readyState === “complete” immediately call the callback function. In this case the function will output the log “DOM is ready…1” message to the console. Otherwise we create an array of callback function to be executed when the DOM is ready.
Step 3 – Attaching the DOMContentLoaded event to the document object.
In this step we will attach the event listener, “DOMContentLoaded” to the document object.
The complete source code is shown below.
(function (window, undefined) {
let domReadyQueue = []; // FIFO
// Define a ready handler
const handleDOMReady = (fn) => {
return document.readyState === "complete"
? fn.call(document)
: domReadyQueue.push(fn);
}
document.addEventListener("DOMContentLoaded", function onDOMReady() {
document.removeEventListener("DOMContentLoaded", onDOMReady);
while(domReadyQueue.length) {
domReadyQueue.shift().call(document);
}
})
const Q = function (selector) {
if (typeof selector === "function") {
return handleDOMReady(selector);
}
}
window.Q = Q;
}(window));
EXAMPLE – DOM ready function
When you execute the below code, the logs will be printed in the console when the DOM is ready to be manipulated.
Q(() => {
console.log("DOM is ready...1");
});
Q(() => {
console.log("DOM is ready...2");
});