Home > Software design >  Load JavaScript before html page
Load JavaScript before html page

Time:11-11

Im learning JS basics and I need to my html page loads before JS if its possible, I`ve tried

document.addEventListener("DOMContentLoaded", function(event) { code here });

But it didnt work, I also tried to put my "script" link in my html body but it didnt change anything, tried to type "defer" in "script", nothing happened.

JS code

var lbs = prompt("What is the weight in pounds (lbs)?")
var kg = pounds * 0.454
alert("That is: "   kg   " kilograms")
console.log("Conversion completed")

HTML code is just a body with simple Lorem text in p tag

CodePudding user response:

Normally, you should add it in the bottom of the body

<html>
    <head>
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>CRP</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <!-- content -->
        <script src="script.js"></script>
    </body>
</html>

CodePudding user response:

DOMContentLoaded event should work. It will be triggered after whole DOM on page is loaded. Maybe try window load event. It will be triggered after the whole page with all references (images, etc.) will be loaded.

Debug all errors you have, like you are using lbs variable and then the pounds variable that is not initialized in your code.

window.addEventListener("load", (e) => {});
document.addEventListener("DOMContentLoaded", (e) => {});
  • Related