Visual Studio Code - Link Javascript file to HTML file

21,691

Solution 1

alert("page is loaded");
<!DOCTYPE html>
    <html>
    <head>
    
    <link rel="stylesheet" href="css.css" type="text/css">
    </head>
    <body>
    <p id="firstParagraph">Hello world!</p>    
    <script src='js.js'></script>
    </body>
    </html>

Note: as a friendly advice, always locate your own javascript files right before closure tag of body, because then they will run after all context is being loaded.

Solution 2

Put your script inside <script> tag and replace

<link rel="stylesheet" href="js.js" type="text/Javascript">

with

<script src="js.js"></script>
Share:
21,691
עדי ביננבאום
Author by

עדי ביננבאום

Updated on October 28, 2020

Comments

  • עדי ביננבאום
    עדי ביננבאום over 3 years

    I'm trying to create an alert in JavaScript when HTML page is loaded.

    I linked the JavaScript file to the HTML file, but the alert doesn't appear.

    What am I doing wrong?

    The CSS file links successfully to the HTML file, and there are no errors on the developer tools on Chrome.

    Code

    alert("page is loaded");
    <!DOCTYPE html>
        <html>
        <head>
        <link rel="stylesheet" href="js.js" type="text/Javascript">
        <link rel="stylesheet" href="css.css" type="text/css">
        </head>
        <body>
        <p id="firstParagraph">Hello world!</p>
        </body>
        </html>
    • DevProf
      DevProf over 5 years
      Please use <script src="your file path"></script> tags to include javascript code in your file.