Skip to content Skip to sidebar Skip to footer

Script Is Before /body But It Runs Before Page Is Loaded

I am new to web developing and I am trying node.js with express. I have the following directory structure: First App ----node_modules ----public --------scripts ------------additem

Solution 1:

The problem that the javascript is being run before the page is loaded

I know this because the alert message is appearing before anything else.

You can't be blamed for coming to that conclusion, but it's actually not the case.

alert()'s are processed by the operating system asynchronously from the JavaScript that spawned them and can usually be rendered faster than the JavaScript can execute. Additionally, an alert() is a "blocking" API call, it freezes the UI so that rendering doesn't sync up with processing.

Instead of an alert() use a console.log(). You will find that doing so shows that your code is running when it should.

Here's an example of how an alert() can mislead your interpretation of the flow of a sequence.

console.clear();
console.log("test before alert()");
alert("Look at the console. Notice how you don't see the log message that came before me?\nEven though the JavaScript received the instruction to write to the console, the OS can render an alert() faster than that.");

Here's the same concept again, but this time without offloading any work to the OS:

console.clear();
console.log("test before console.log()");
console.log("Look at the console. Notice how you now do see the log message that came before me?");

Solution 2:

Having your script at the end of the body is an outdated pattern. You should prefer to load the script in the head with the defer attribute (read more https://mdn.io/script). If you can't do that, in your script you may use a load listener to delay execution until all loading is complete.

window.addEventListener('load', () => {console.log('tada!')});

Solution 3:

It takes time for the browser to parse your HTML and build the DOM, and your script will start running as soon as it is encountered, so basically you're setting up a race and hoping the js interpreter loses. Not a reliable way to run asynchronous code.

Post a Comment for "Script Is Before /body But It Runs Before Page Is Loaded"