Skip to content

Inline vs External Scripts for Web Pages

Before learning the basics of JavaScript, let's first understand the difference between inline and external scripts.

Inline JavaScript: code inside HTML pages

An inline script is JavaScript code written directly within the HTML code of a web page.

Example:

<body>
    <!-- Some HTML elements -->
    <script>
        console.log("Hello world!");
    </script>
    <!-- Some other HTML elements -->
</body>

External JavaScript: code outside of HTML pages

An external script is JavaScript code written in a separate JavaScript file which gets executed within an HTML page.

To execute an external script from an HTML page/file, you need to create a separate JavaScript file (.js) and then link it to your HTML file. Here’s a step-by-step guide:

  1. Create a JavaScript file: Write your JavaScript code in a text editor and save the file with a .js extension. For example, you might name it script.js.
// script.js
function sayHello() {
    alert('Hello, World!');
}
  1. Link the JavaScript file to your HTML file: You can use the <script> tag in your HTML file to link to the JavaScript file. The src attribute should contain the path to your JavaScript file.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>My Web Page</title>
</head>
<body>
    <h1>Welcome to My Web Page</h1>
    <button onclick="sayHello()">Click me</button>

    <!-- Link to the JavaScript file -->
    <script src="script.js"></script>
</body>
</html>

In the above HTML file, the sayHello function defined in the script.js file is called when the button is clicked.

Remember, the path in the src attribute should be relative to the HTML file. If your JavaScript file is in a different directory, you’ll need to include the directory path (e.g., src="scripts/script.js").

Also, it’s a good practice to place the <script> tag just before the closing </body> tag. This is because the browser parses the HTML from top to bottom, and placing the <script> tag at the end allows the HTML to load before the JavaScript. This can prevent potential issues with JavaScript trying to manipulate HTML elements that haven’t loaded yet.