TheBrahminCoder - What is script tag and types of scripts
In web development, the `<script>` tag is used to define and embed scripts within an HTML document. It allows you to include JavaScript code directly in the HTML file or reference external JavaScript files. The `<script>` tag is typically placed within the `<head>` or `<body>` section of an HTML document.
There are three main types of scripts that can be used in web development:
1. Inline Scripts:
Inline scripts are written directly within the `<script>` tags in the HTML document. Here's an example:
Inline scripts are convenient for small snippets of code or when the script is specific to that particular HTML document. However, using too many inline scripts can make the HTML file cluttered and harder to maintain.
2. External Scripts:
External scripts are JavaScript files that are referenced using the `<script>` tag's `src` attribute. The `src` attribute specifies the path to the external script file. Here's an example:
The `script.js` file contains the JavaScript code and should be stored in the same directory as the HTML file or the correct relative path should be provided. External scripts promote code reusability and maintainability, as they can be shared across multiple HTML files.
3. Asynchronous and Deferred Scripts:
JavaScript can be loaded asynchronously or deferred to enhance webpage performance.
- Asynchronous Scripts:
Asynchronous scripts are loaded and executed simultaneously while the HTML parsing and rendering continue. They don't block the rendering of the page. To load a script asynchronously, you can use the `async` attribute in the `<script>` tag. Here's an example:
- Deferred Scripts:
Deferred scripts are also loaded asynchronously but are executed after the HTML parsing is complete. They don't block the rendering of the page. To load a script as deferred, you can use the `defer` attribute in the `<script>` tag. Here's an example:
Note that the order of execution is maintained for multiple deferred scripts, while asynchronous scripts may execute in any order.
These are the common types of scripts used in web development. They provide flexibility in embedding and organizing JavaScript code within HTML documents, allowing for interactivity, dynamic behavior, and enhanced functionality on web pages.
Comments
Post a Comment