Home Web Front-end HTML Tutorial What is the role of script tag in HTML? What is the usage of type attribute in script tag?

What is the role of script tag in HTML? What is the usage of type attribute in script tag?

Aug 16, 2018 pm 06:02 PM

What is the role of the

script tag in HTML? What is the usage of type attribute in script tag? This article mainly explains the relevant knowledge and functions of the HTML Script tag and the usage of the type attribute in the script tag.

Related knowledge and functions of the HTML Script tag:

How much do you know about script, a frequently used tag? With the improvement of this script tag, some HTML5 things have been added, such as async and defer, crossorigin, for / event, etc.

As you may know, the script tag is used to specify which JavaScript is executed on the web page. Script tags can contain JavaScript code directly, or point to a JavaScript external URL.

Script tags are executed in the order they appear. The following code illustrates this intuitively:

<script>
  var x = 3;
</script>
<script>
  alert(x);
  // Will alert &#39;3&#39;;
</script>
Copy after login

The loading order is not so intuitive when using external link resources, but it is still true. :

<script src="//typekit.com/fj5j4j3.js"></script>
<!-- 在Type套件已执行或超时之前,此第二脚本不会执行。 -->
<script src="//my.site/script.js"></script>
Copy after login

The same rule applies if you mix external links and inline JavaScript.

This means that if your website has slow scripts that are loaded earlier in the page, your page loading will be significantly slower. This also means that scripts loaded later can depend on scripts loaded earlier.

The page element will not be rendered until all scripts before it have been loaded. This means that you can do all kinds of crazy things on your web pages before they load, as long as you don't care about the performance issues this causes.

However, this rule does not apply to adding script tags to the DOM through methods such as document.appendChild after the web page is loaded. These tags will execute the scripts in the order in which the browser request processing is completed, and the loading order is no longer guaranteed.

When a script tag is executed, the HTML elements before it can be accessed (but those after it are not yet available)

<html>
  <head>
    <script>
      // document.head is available
      // document.body is not!
    </script>
  </head>
  <body>
    <script>
      // document.head is available
      // document.body is available
    </script>
  </body>
</html>
Copy after login

You can imagine the HTML parser accessing tag by tag document, when it parses the script tag, the JavaScript in it is immediately executed. This means that only DOM nodes whose start tag appears before the current script can be accessed in the current JavaScript (via querySelectorALl, jQuery, etc.).

A useful corollary is that document.head is almost always available in any JavaScript written on a web page. document.body is only available if you write the script tag inside or after the tag.

HTML5 adds two tools to control script execution.

async means "you don't need to execute it immediately". More specifically it says: I don't mind if you execute this script after the entire page has loaded, putting it after other scripts. This is very useful for statistical analysis scripts because no other code on the page needs to depend on the statistics script execution. Defining variables or functions that a page needs is not possible in async code because you have no way of knowing when the async code will actually be executed.

defer means "wait for the page to be parsed before executing". It's roughly equivalent to binding your script to the DOMContentedLoaded event, or using jQuery.ready. When this code is executed, all elements in the DOM are available. Unlike async, all defer scripts will be executed in the order they appear in the HTML page, it is just postponed until the HTML page is parsed.

Usage of the type attribute in the script tag in html:

Historically (since the birth of Netsacpe 2), whether to write type= on the script tag text/javascript has nothing to do with it. If you set a non-JavaScript MIME type via type, the browser will not execute it. This is cool when you want to define your own language:

<script type="text/emerald">
  make a social network
    but for cats
</script>
Copy after login

The actual execution result of this code is up to you, such as:

<script>
  var codez = document.querySelectorAll(&#39;script[type="text/emerald"]&#39;);
  for (var i=0; i < codez.length; i++)
    runEmeraldCode(codez[i].innerHTML);
</script>
Copy after login

The definition of runEmeraldCode function is left to you as practise.

If you have special needs, you can also override the default type of the script tag on the page by passing a meta tag:

<meta http-equiv="Content-Script-Type" content="text/vbscript">
Copy after login

or a request returning a Content-Script-Type header.

You can use crossorigin

Although it has not been fully standardized, some browsers support the crossorigin attribute. The basic idea is that the browser will restrict the use of non-original resources (homologous resources are the same protocol, hostname and port, for example: `http://google.com:80).

This is to prevent you from, for example, making a request to your competitor's website to log out your user's account on that website (this is not good!). Although it is a bit unexpected that this problem involves the script tag, if crossorigin is implemented, you only need to add a handler to the window.onerror event, and you will see some warning messages on the console, prompting you to introduce something that should not be introduced. Outsite scripts. Under secure browsers, loading external scripts will work without error unless you specify the crossorigin attribute.

crossorgin is not a magic security trick, all it does is make the browser enable normal CORS access checks, make an OPTIONS request and check the Access-Control header.

html Script tag and innerHTML:

通过 DOM 动态添加到页面上的 script 标签会被浏览器执行:

var myScript = document.createElement(&#39;script&#39;);
myScript.textContent = &#39;alert("?")&#39;;
document.head.appendChild(myScript);
Copy after login

通过 innerHTML 动态添加到页面上的 script 标签则不会被执行:

document.head.innerHTML += &#39;<script>alert("?")</script>&#39;;
Copy after login

为什么会是这样的原因不是很确定,但是它解决了一个小问题:“是否有一个办法让一个 script 标签在 Chrome 代码检查器中显示但不实际执行?”

【相关推荐】

HTML5中web是什么?web存储中的元素有哪些?

HTML table属性你知道多少,进来了解一下?


The above is the detailed content of What is the role of script tag in HTML? What is the usage of type attribute in script tag?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

See all articles