A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/html/html-defer-attribute/ below:

HTML defer Attribute - GeeksforGeeks

HTML defer Attribute

Last Updated : 18 Dec, 2024

The defer attribute can be added to <script> elements that point to an external JavaScript file. It ensures that the script is executed only after the HTML document has been completely loaded and parsed, but before the DOMContentLoaded event is fired.

html
<html>
<body>
    <script id="myGeeks"
            type="text/javascript"
            src="my_script.js"
            defer>
    </script>
    <br>
    <button type="button" onclick="myFunction()">Submit</button>
</body>
</html>
JavaScript
function myFunction() {
    alert("Script works");
}

In this example:

Syntax
<script src="script.js" defer></script>
How It Works

When the browser encounters a <script> tag with the defer attribute:

Example Without defer (Blocking Script): HTML
<html>
<head>
    <script src="script.js"></script>
</head>
<body>
    <h1>This text is delayed!</h1>
         <button type="button" onclick="myFunction()"> Submit </button>
</body>
</html>
JavaScript
function myFunction() {
    alert("Script works");
}
Example With defer: HTML
<html>
<head>
  <script src="script.js" defer></script>
</head>
<body>
    <h1>This text loads without delay!</h1>
         <button type="button" onclick="myFunction()">Submit</button>
</body>
</html>
JavaScript
function myFunction() {
    alert("Script works");
}
Why Use the defer Attribute? Key Features of the defer Attribute

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4