HTML “ < script > ” tag-execute JavaScript code



 The <script> tag is used to write JavaScript . You can write JavaScript code directly (inline) in <sciprt>, or use <script> to load external JavaScript program files.

For example, the usage of directly writing JavaScript code:

<script>
function hello() {
  alert('hello world!');
}
</script>

If it is used to load an external JavaScript file, use the src attribute (attribute) of <script> to specify the file address (URL), and leave the tag content blank:

<script src="somescript.js"></script>

When the browser reaches the above line of <script> tag, it will pause first, wait for the JavaScript file to be downloaded and execute the content of the file, and then continue to execute other HTML.

<script src = ""> There are two properties asyncand defercan be used to allow JavaScript file can be asynchronous (asynchronously) loaded and executed, meaning that the browser without waiting for the JavaScript files loaded, you can continue with other HTML down .

asyncAnd deferusage is slightly different:

  • async is to make JavaScript files loaded asynchronously, but if there are multiple scripts, the order of execution is not guaranteed
  • Defer is to load the JavaScript file asynchronously, and it will be executed after the entire HTML file is parsed. At the same time, defer will ensure that the order of execution is in accordance with the order of different scripts.

Usage example:

<script async src="script-1.js"></script>
<script async src="script-2.js"></script>

Another attribute is charsetused to indicate the encoding of external files, because most encodings are now UTF-8 by default, so they are not so commonly used:

<script src="myscripts.js" charset="UTF-8"></script>

Post a Comment

0 Comments