Document ready
A lot of things happen asynchronously in the web browser. As the page loads, resources are being fetched and rendered, executed and so forth. In principle, our Javascript might be executed before the document is ready. That is, before its structure is in place.
If we want to do anything with the HTML elements (which is usually the case), it's important to wait for the document to be ready before doing whatever we want to do.
Therefore, add the following snippet to the top of your script file:
if (document.readyState != 'loading'){
onDocumentReady();
} else {
document.addEventListener('DOMContentLoaded', onDocumentReady);
}
function onDocumentReady() {
console.log("Ready!");
}
Whatever is inside of the onDocumentReady
function will run when the document is ready. For now we just have a test message for ourselves to make sure it works. Within this function is where you'll want to listen to events, and kick start any behaviour you like.
How it works
You can skip over how it works, but if you really want to know...
First the state of the document is checked - perhaps by the time the script runs the document is already loaded. If that's the case, we jump ahead and call onDocumentReady
. If not, we listen to the 'DOMContentLoaded' event on the document
object, calling onDocumentReady
when it fires. Finally our function is defined, containing just the console.log
line.