<" /> <" /> <"/>

external js file loaded but the code don't working

425 views Asked by At

when I write js code internally in the html file It's work well. hre is the html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="./cs.css" rel="stylesheet">
    <title>Document</title>
</head>
<body>
   <div id="root" onload="App">
   

</div>
<script src="js/App.js" type="module" />
</body>
</html>

and here is App.js file

import Insert from './Insert.js';
function App(){
  document.getElementById("root").insertAdjacentHTML("afterbegin",'<h1>hello Javascript</h1>');
}; 
1

There are 1 answers

2
Quentin On
  1. onload is not an attribute supported by div elements, generally if you use it you would apply it to the body element, but it should be avoided in favour of addEventListener
  2. The value of the onload attribute is the body of a JS function. Just mentioning the name of another function doesn't do anything. If you want to call a function you would usually follow the name with ().
  3. type="module" loads a JS module, which (among other things) means the outer scope is the module and not the global scope so you can't access App anyway. Again, use addEventListener.
  4. The </script> end tag for the script element is mandatory and you omitted it. (Since it was that last thing in the document it probably won't break anything, but you are opening yourself up for future problems).