[HTML][JS] multiple script tags in a HTML page
Can You Use Multiple <script> Tags in One HTML Page?
How did I encounter this?
<script> blocks in a single HTML page? Multiple <script> Tags Are Allowed
It is completely valid to include more than one <script> tag in a single HTML document. In fact, this is quite common in real-world development.
For example:
-
A
<script>in the<head>to initialize some global settings. -
Another
<script>near the bottom to handle user interactions. -
External scripts loaded via
<script src="...">.
All of these work together — as long as they're placed and structured properly.
Multiple script blocks on the same page share the same global scope.
-
Variables declared with
let,const, orvaroutside of functions are accessible across all script blocks. -
Functions defined in one block can be called in another.
-
They execute in the order they appear in the HTML.
Example
<!-- First script block --><script> let gameTitle = "Elden Ring"; function displayTitle() { console.log("Game:", gameTitle); }</script>
<!-- Second script block --><script> displayTitle(); // Output: Game: Elden Ring</script>
In this example, the second script can access both the variable and function from the first block because they exist in the same global JavaScript environment.
Things to be aware of
-
Execution Order Matters
If a function is used before it’s declared in an earlier script block, it will cause an error. -
Avoid Global Pollution
Too many variables in the global scope can cause conflicts or hard-to-trace bugs. It’s a good habit to encapsulate logic or use modules (especially for larger projects).
Best Practice
If the project is growing, consider:
-
Using external
.jsfiles and importing them using<script src="..."> -
Wrapping code in functions or using ES6 modules
-
Keeping related code grouped to avoid confusion
Comments
Post a Comment