Home > Article > Web Front-end > Learn about the script tag in HTML
Students who have learned a little bit about web page writing all know that the js code in the web page should be written in the script tag, but why do you do this? This article will introduce the script tag.
Initially, Netscape wanted to display HTML files using js in the browser, but did not want to affect the display effect of this file in other browsers, so it created script tag
We all know that tags can add attributes to it. The script tag has the following attributes:
<script type="text/javascript"> // 属性设置 function SayHi(){ alert("Hi"); } </script>
<!-- 注意下面的写法 /> 这么写本身没有问题,但是不能在html中使用这种语法,因为这样会打乱html的解析 --> <script type="text/javascript" src="2.js"/> // 必须写成下面的样子 <script type="text/javascript" src="2.js"></script>
Note:
Originally, the tag should be placed in the header, but because it is placed in the header, the page will not be rendered when js is loaded (the page will not start rendering until it is loaded into the body), causing the page to appear for a long time. Bai, so now we put it at the end of the body
<body> ... <script src="1.js"></script> <script src="2.js"></script> <script src="3.js"></script> </body>
After adding the defer attribute to the script, putting it in the header can theoretically achieve the purpose of delayed execution, but because different browsers have different support for defer ( The execution order is uncertain, embedded js does not support defer, etc.), it is best for us to follow the above writing method and write it at the end of the body .
The async attribute is also to solve the problem of asynchronous loading of scripts. It also does not support embedded js scripts. Originally, the difference between it and defer is that defer loads in order, async does not load in order, but in actual use, Browsers also have different support for this attribute. Neither attribute can guarantee the sequential execution of scripts and execution before DOMContentLoaded, so it is best not to use this attribute until the browser fully supports it.
When the browser disables js or the browser does not support js at all (of course this is rare now), it needs to be degraded smoothly, so the noscript tag
is needed The function is to display the content in noscript when the situation mentioned above occurs. See the example below
<html> <head> <script src="2.js"></script> </head> <body> <noscript> <p>本页面需要浏览器支持(启用)JavaScript</p> </noscript> </body> </html>
Note that if the browser has JS enabled, the content in this tag will not be displayed.
Recommended tutorials: HTML tutorial, JavaScript video tutorial
The above is the detailed content of Learn about the script tag in HTML. For more information, please follow other related articles on the PHP Chinese website!