


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 PMWhat 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 '3'; </script>
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套件已執(zhí)行或超時之前,此第二腳本不會執(zhí)行。 --> <script src="//my.site/script.js"></script>
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>
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>
The actual execution result of this code is up to you, such as:
<script> var codez = document.querySelectorAll('script[type="text/emerald"]'); for (var i=0; i < codez.length; i++) runEmeraldCode(codez[i].innerHTML); </script>
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">
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 動態(tài)添加到頁面上的 script 標簽會被瀏覽器執(zhí)行:
var myScript = document.createElement('script'); myScript.textContent = 'alert("?")'; document.head.appendChild(myScript);
通過 innerHTML 動態(tài)添加到頁面上的 script 標簽則不會被執(zhí)行:
document.head.innerHTML += '<script>alert("?")</script>';
為什么會是這樣的原因不是很確定,但是它解決了一個小問題:“是否有一個辦法讓一個 script 標簽在 Chrome 代碼檢查器中顯示但不實際執(zhí)行?”
【相關推薦】
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to keep up with HTML standards and best practices is to do it intentionally rather than follow it blindly. First, follow the summary or update logs of official sources such as WHATWG and W3C, understand new tags (such as) and attributes, and use them as references to solve difficult problems; second, subscribe to trusted web development newsletters and blogs, spend 10-15 minutes a week to browse updates, focus on actual use cases rather than just collecting articles; second, use developer tools and linters such as HTMLHint to optimize the code structure through instant feedback; finally, interact with the developer community, share experiences and learn other people's practical skills, so as to continuously improve HTML skills.

The reason for using tags is to improve the semantic structure and accessibility of web pages, make it easier for screen readers and search engines to understand page content, and allow users to quickly jump to core content. Here are the key points: 1. Each page should contain only one element; 2. It should not include content that is repeated across pages (such as sidebars or footers); 3. It can be used in conjunction with ARIA properties to enhance accessibility. Usually located after and before, it is used to wrap unique page content, such as articles, forms or product details, and should be avoided in, or in; to improve accessibility, aria-labeledby or aria-label can be used to clearly identify parts.

To create a basic HTML document, you first need to understand its basic structure and write code in a standard format. 1. Use the declaration document type at the beginning; 2. Use the tag to wrap the entire content; 3. Include and two main parts in it, which are used to store metadata such as titles, style sheet links, etc., and include user-visible content such as titles, paragraphs, pictures and links; 4. Save the file in .html format and open the viewing effect in the browser; 5. Then you can gradually add more elements to enrich the page content. Follow these steps to quickly build a basic web page.

To create an HTML checkbox, use the type attribute to set the element of the checkbox. 1. The basic structure includes id, name and label tags to ensure that clicking text can switch options; 2. Multiple related check boxes should use the same name but different values, and wrap them with fieldset to improve accessibility; 3. Hide native controls when customizing styles and use CSS to design alternative elements while maintaining the complete functions; 4. Ensure availability, pair labels, support keyboard navigation, and avoid relying on only visual prompts. The above steps can help developers correctly implement checkbox components that have both functional and aesthetics.

To reduce the size of HTML files, you need to clean up redundant code, compress content, and optimize structure. 1. Delete unused tags, comments and extra blanks to reduce volume; 2. Move inline CSS and JavaScript to external files and merge multiple scripts or style blocks; 3. Simplify label syntax without affecting parsing, such as omitting optional closed tags or using short attributes; 4. After cleaning, enable server-side compression technologies such as Gzip or Brotli to further reduce the transmission volume. These steps can significantly improve page loading performance without sacrificing functionality.

HTMLhasevolvedsignificantlysinceitscreationtomeetthegrowingdemandsofwebdevelopersandusers.Initiallyasimplemarkuplanguageforsharingdocuments,ithasundergonemajorupdates,includingHTML2.0,whichintroducedforms;HTML3.x,whichaddedvisualenhancementsandlayout

It is a semantic tag used in HTML5 to define the bottom of the page or content block, usually including copyright information, contact information or navigation links; it can be placed at the bottom of the page or nested in, etc. tags as the end of the block; when using it, you should pay attention to avoid repeated abuse and irrelevant content.

ThetabindexattributecontrolshowelementsreceivefocusviatheTabkey,withthreemainvalues:tabindex="0"addsanelementtothenaturaltaborder,tabindex="-1"allowsprogrammaticfocusonly,andtabindex="n"(positivenumber)setsacustomtabbing
