HTML Script src Property: Linking External JavaScript Files

The HTML <script> tag is used to embed or reference executable code, typically JavaScript, within an HTML document. The src attribute of the <script> tag specifies the URL of an external script file that the browser should fetch and execute. This method is crucial for organizing and reusing JavaScript code across multiple web pages.

What is the src Property?

The src property defines the source URL of an external script file. It allows you to link your HTML document to a separate JavaScript file, which promotes cleaner code, reusability, and maintainability.

Purpose of the src Property

The primary purpose of the src property is to:

  • Include external JavaScript files in an HTML document.
  • Enable code reusability by referencing the same script file in multiple pages.
  • Improve code organization by separating JavaScript code from HTML markup.
  • Facilitate easier maintenance and updates of JavaScript code.

Syntax

The syntax for using the src property within the <script> tag is as follows:

<script src="URL"></script>

Attributes

Attribute Type Description
`src` URL Specifies the URL of the external script file. The URL can be absolute or relative.

Examples

Let’s explore some practical examples of using the src property to include external JavaScript files in your HTML document.

Basic Usage

This example demonstrates the simplest way to include an external JavaScript file using the src property.

First, create an external JavaScript file named script_basic.js with the following content:

// script_basic.js
document.addEventListener("DOMContentLoaded", function() {
    alert("Hello from external script!");
});

Then, include this script in your HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Basic src Example</title>
</head>
<body>
    <h1>Basic src Example</h1>
    <script src="script_basic.js"></script>
</body>
</html>

Output:

An alert box will appear when the page loads, displaying “Hello from external script!”.

Relative URL

This example uses a relative URL to reference the script file. Relative URLs are relative to the current HTML document’s location.

Assuming the script_relative.js file is in the same directory as the HTML file, the code will be:

Create an external JavaScript file named script_relative.js with the following content:

// script_relative.js
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("relativeMessage").textContent = "Message from relative script!";
});

Then, include this script in your HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Relative src Example</title>
</head>
<body>
    <h1>Relative src Example</h1>
    <p id="relativeMessage"></p>
    <script src="script_relative.js"></script>
</body>
</html>

Output:

The paragraph with the ID “relativeMessage” will display “Message from relative script!”.

Absolute URL

This example uses an absolute URL to reference the script file. Absolute URLs provide the full path to the script file, regardless of the HTML document’s location.

Create an external JavaScript file hosted on a server named script_absolute.js with the following content:

// script_absolute.js
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("absoluteMessage").textContent = "Message from absolute script!";
});

Then, include this script in your HTML file, replacing "https://your-domain.com/script_absolute.js" with the actual URL of your script:

<!DOCTYPE html>
<html>
<head>
    <title>Absolute src Example</title>
</head>
<body>
    <h1>Absolute src Example</h1>
    <p id="absoluteMessage"></p>
    <script src="https://your-domain.com/script_absolute.js"></script>
</body>
</html>

Output:

The paragraph with the ID “absoluteMessage” will display “Message from absolute script!”.

Using src with async

The async attribute allows the script to be fetched and executed asynchronously, without blocking the parsing of the HTML document.

Create an external JavaScript file named script_async.js with the following content:

// script_async.js
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("asyncMessage").textContent = "Message from async script!";
});

Then, include this script in your HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Async src Example</title>
</head>
<body>
    <h1>Async src Example</h1>
    <p id="asyncMessage"></p>
    <script src="script_async.js" async></script>
</body>
</html>

Output:

The paragraph with the ID “asyncMessage” will display “Message from async script!”. The script is fetched and executed asynchronously.

Using src with defer

The defer attribute defers the execution of the script until the HTML document has been fully parsed.

Create an external JavaScript file named script_defer.js with the following content:

// script_defer.js
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("deferMessage").textContent = "Message from defer script!";
});

Then, include this script in your HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Defer src Example</title>
</head>
<body>
    <h1>Defer src Example</h1>
    <p id="deferMessage"></p>
    <script src="script_defer.js" defer></script>
</body>
</html>

Output:

The paragraph with the ID “deferMessage” will display “Message from defer script!”. The script is executed after the HTML document has been fully parsed.

Real-World Application: Including a Library

A common real-world application of the src property is to include external JavaScript libraries, such as jQuery, in your HTML document.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Example</title>
</head>
<body>
    <h1>jQuery Example</h1>
    <p id="jqueryMessage"></p>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#jqueryMessage").text("Message from jQuery!");
        });
    </script>
</body>
</html>

Output:

The paragraph with the ID “jqueryMessage” will display “Message from jQuery!”. This example demonstrates how to include and use the jQuery library.

Best Practices

  • Use External Files: Always use external JavaScript files with the src property for better code organization and reusability.
  • Specify Correct Paths: Ensure the src attribute contains the correct URL to the script file, whether it’s a relative or absolute path.
  • Use async or defer: Use the async or defer attributes to optimize page loading and rendering performance.
  • Load Order: Be mindful of the load order of your scripts, especially when using libraries or scripts that depend on each other.
  • Error Handling: Implement error handling to gracefully manage cases where the script file cannot be loaded or executed.

Browser Support

The src property of the <script> tag is supported by all modern web browsers.

Conclusion

The src property of the HTML <script> tag is essential for including external JavaScript files in your web pages. By using external files, you can improve code organization, reusability, and maintainability. Whether you’re referencing local scripts or external libraries, understanding how to use the src property effectively is crucial for modern web development. 🚀