loading

The most optimal JS solution for loading on the page.

Check out how to use cross-browser and optimal loading to check if the document has loaded with vanilla Javascript using this property.

And the answer is  document.readyState property!

I have tried o lot of solutions, but the cross-browser and optimal way to check if the document has loaded, and uses vanilla javascript is readyState.

The document.readyState property describes the loading state of the document. When the value of this property changes, a readystatechange event fires on the document object.

The document.readyState can tell us tree status of the page load:

Loading

The document is constructing its elements

Interactive

 When the document has finished loading but sub-resources such as stylesheets, images and frames are still loading.

Use document.readyState === 'interactive' to detect when the DOM is ready.

Complete

The document and all resources like images/stylesheets have finished loading.

if (document.readyState === 'complete') {
  // The page is fully loaded
}

Document: readystatechange event

The readystatechange event is fired when the readyState attribute of a document has changed.

The loading code to your page

Combining the complete string and the readystatechange event whe can detect when document.readyState changes, readystatechange event fires and our function executes. If the document is not yet loaded then the body should remain hidden from the user, only the loader should be visible. Once the page has completely loaded we set loader’s display to none and we make the body visible.

document.onreadystatechange = function() {
	if (document.readyState !== "complete") {
		document.querySelector("body").style.visibility = "hidden";
		document.querySelector("#loading").style.visibility = "visible";
	} else {
		document.querySelector("#loading").style.display = "none";
		document.querySelector("body").style.visibility = "visible";
	}
};

To implement this simple, but awesome loading to your page using a loading pure CSS, check out this post.