简体   繁体   中英

Load JavaScript before html page

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

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>

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) => {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM