HTML
HTML script Tag: The Script Element
The HTML <script>
tag embeds executable scripts within an HTML document. Most commonly, the script element contains JavaScript code or refers to files with JavaScript code.
How to Use the Tag in HTML
The <script>
tag can either embed JavaScript or link to an external JavaScript file.
Embedding JavaScript Code
You can write JavaScript code directly within a <script>
tag in an HTML document.
<script>
alert("Welcome to our website!");
</script>
<script>
: The tag to embed a script in HTML.
Linking External JavaScript Files
Alternatively, you can link to an external JavaScript file using the src
attribute.
<script src="path/to/your-script.js"></script>
<script>
: The tag to embed a script in HTML.src
: The attribute to specify the URL of the external script file.
When to Use the Tag in HTML
The <script>
tag is essential for integrating JavaScript into HTML documents to create interactive and dynamic web pages.
Interactive Elements
JavaScript enhances HTML with interactivity, making web pages responsive to user actions.
<button onclick="alert('Hello!')">Click Me!</button>
Form Validation
JavaScript is used for client-side form validation before submitting data to a server.
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
Dynamic Content
JavaScript can modify the content of a web page on the fly without needing to reload the page.
<script>
function changeText() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
<p id="demo">JavaScript can change this text.</p>
<button onclick="changeText()">Click me to change the text</button>
Examples of the Tag in HTML
Most interactive and dynamic web pages need the <script>
tag to execute JavaScript code. Here are some simplified examples:
Toggle Product Details
An e-commerce website might use JavaScript to toggle product details visibility.
<script>
function toggleDetails() {
const details = document.getElementById("productDetails");
details.style.display = details.style.display === "none" ? "block" : "none";
}
</script>
<h3>Product Name</h3>
<button onclick="toggleDetails()">Toggle Details</button>
<div id="productDetails" style="display: none;">
<ul>
<li>Color: Red</li>
<li>Size: Medium</li>
<li>Weight: 1.2 kg</li>
</ul>
</div>
Load Frameworks and Libraries
A portfolio website might include popular JavaScript frameworks like jQuery to extend functionality.
<!DOCTYPE html>
<html>
<head>
<title>My Portfolio</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Welcome to My Portfolio</h1>
<button id="clickMe">Click Me</button>
<script>
$("#clickMe").on("click", function() {
alert("You clicked the button!");
});
</script>
</body>
</html>
Analytics and Tracking
A business website can use tracking scripts like Google Analytics to gather insights about traffic.
<!DOCTYPE html>
<html>
<head>
<title>Business Insights</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
</script>
</head>
<body>
<h1>Welcome to Our Business</h1>
</body>
</html>
Load Asynchronous Scripts
A blog website can use asynchronous loading for a better user experience and faster page load.
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
<script async src="scripts/blog-analytics.js"></script>
</head>
<body>
<h1>Welcome to My Blog</h1>
<p>Here you can find articles on web development and tech.</p>
</body>
</html>
Learn More About the Tag in HTML
Script Loading Strategies
Understanding different script loading strategies can significantly impact the performance and behavior of web pages.
-
Synchronous Loading: Scripts are executed in the order they appear. It can block page rendering until execution is complete.
-
Asynchronous Loading: Using the
async
attribute ensures the script is fetched asynchronously and executed as soon as it's ready.<script async src="script.js"></script>
-
Deferred Loading: The
defer
attribute delays script execution until the page's HTML content is fully loaded.<script defer src="script.js"></script>
Inline vs External JavaScript
Decide when to use inline JavaScript and when to link to external script files based on page size, script reusability, and maintenance considerations.
-
Inline JavaScript: Useful for quick scripts and prototyping.
<script> console.log("Inline JavaScript executed"); </script>
-
External JavaScript: Ideal for reusable and maintainable code.
<script src="scripts/main.js"></script>
Security Considerations
Secure your scripts to prevent vulnerabilities like Cross-Site Scripting (XSS). Use Content Security Policies (CSP) and Subresource Integrity (SRI) to mitigate risks.
<!-- Example CSP policy -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://example.com">
<!-- Example SRI -->
<script src="https://example.com/script.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxjMRUeRRsYqnlpYPXQXOeYa9FZ9lFz" crossorigin="anonymous"></script>
The type Attribute
Within the <script>
tag, the type
attribute specifies the MIME type of the script. Since JavaScript has become the default scripting language, setting type
is no longer necessary. Before HTML5, you needed to set the type
attribute to "text/javascript"
.
<script type="text/javascript">
console.log("JavaScript is running");
</script>
Advanced Features
Explore advanced attributes to optimize how your JavaScript loads:
async
: Loads scripts asynchronously to prevent blocking page rendering.defer
: Defers script execution until the page content is loaded.nomodule
: Ensures modern browsers ignore older scripts meant for legacy browsers.
htmlCopy code
<!-- Example: Asynchronous loading -->
<script async src="modern-analytics.js"></script>
<!-- Example: Deferred loading -->
<script defer src="legacy-analytics.js"></script>
<!-- Example: Exclude scripts from modern browsers -->
<script nomodule src="legacy-polyfill.js"></script>
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.