As you probably know, the <script> tag is used to specify which JavaScript to execute on a web page. The <script> tag can contain JavaScript code directly or point to a JavaScript external URL. </script>
<script>The tags are executed in the order in which they appear</script>
The following code illustrates this intuitively:
<script> var x = 3; </script> <script> alert(x); // Will alert '3'; </script>
There is no loading order when using external link resources So intuitive, but still true:
<script src="//typekit.com/fj3j1j2.js"></script> <!-- This second script won’t execute until typekit has executed, or timed out --> <script src="//my.site/script.js"></script>
Related learning recommendations: javascript video tutorial
If you mix external links and inline links For JavaScript, the same rule applies.
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 you adding <script> tags to the DOM through methods such as <code>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. </script></p> <h3 id="-script-html-">When a <script> tag is executed, the HTML elements before it are accessible (but those after it are not yet available) </script> </h3><pre class='brush:php;toolbar:false;'>&lt;html&gt; &lt;head&gt; &lt;script&gt; // document.head is available // document.body is not! &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; // document.head is available // document.body is available &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre><p>You can imagine that the HTML parser works one tag at a time Access the document taggedly, and when it parses the <script> tag, execute the JavaScript in it. This means that only DOM nodes whose start tag appears before the current script can be accessed in the current JavaScript (via <code>querySelectorALl, jQuery, etc.). </script></p> <p>A useful corollary is that <code>document.head</code> is almost always available in any JavaScript written on a web page. <code>document.body</code> is only available if you write the <script> tag within or after the <code><body> tag. </script></p> <h3 id="-async-defer-"> <code>async</code> and <code>defer</code> </h3> <p> HTML5 adds two tools to control the execution of scripts. </p> <ul> <li> <code>async</code> means "don't execute it right away". 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 required by a page in <code>async</code> code is not possible because you have no way of knowing when the <code>async</code> code will actually be executed. </li> <li> <code>defer</code> means "wait for the page to be parsed before executing". It is roughly equivalent to binding your script to the <code>DOMContentedLoaded</code> event, or using <code>jQuery.ready</code>. When this code is executed, all elements in the DOM are available. Unlike <code>async</code>, all scripts with <code>defer</code> will be executed in the order they appear in the HTML page, it is just postponed until the HTML page is parsed. </li> </ul> <h3 id="-type-"> <code>type</code> Attribute </h3> <p>Historically (since the birth of Netsacpe 2), whether to write <code>type= on the <script> tag text/javascript</script></code> doesn't matter. If you set a non-JavaScript MIME type via <code>type</code>, the browser will not execute it. This is cool when you want to define your own language: </p><pre class='brush:php;toolbar:false;'><script type="text/emerald"> make a social network but for cats </script></pre><p>The actual execution result of this code is up to you, for example: </p><pre class='brush:php;toolbar:false;'><script> var codez = document.querySelectorAll(&#39;script[type="text/emerald"]&#39;); for (var i=0; i < codez.length; i++) runEmeraldCode(codez[i].innerHTML); </script></pre><p>Definition<code>runEmeraldCode</code> Functions are left as an exercise for you. </p> <p>If you have special needs, you can also override the default <code>type</code> for the <script> tag on the page by passing a <code>meta tag: </script></p><pre class='brush:php;toolbar:false;'>&lt;meta http-equiv=&quot;Content-Script-Type&quot; content=&quot;text/vbscript&quot;&gt;</pre><p> Or a request returns a <code>Content-Script-Type</code> header. </p> <p>You can read a brief history of the strange scripting languages on the Web in this article for more detailed information on <code>type</code> usage. </p> <h3 id="Use-code-integrity-code-attribute-The">Use <code>integrity</code> attribute? The </h3> <p><code>integrity</code> attribute is part of the new specification for subresource integrity. It allows you to provide a hash for the content the script file will contain. This means that content can be prevented from being lost or maliciously modified during transmission. Even if SSL is used, this specification still makes sense, because sometimes the resources you want to load are off-site resources that you have no control over, such as <code>code.jquery.com</code>. </p> <p>If you choose to use it, you need to include a hash type and hash value in the <script> tag, separating them with a hyphen. It looks similar to the following: </script>
<script src="//code.jquery.com/jquery.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"> </script>
我还没有看到有人用了它,然而如果你知道有哪个网站用了,可以在下面评论。
还可以用 crossorigin
!
虽然还没有完全被标准化,但是一些浏览器支持 crossorigin
属性。基本的想法是,浏览器会限制对非同源资源的使用(同源资源是指相同的协议、hostname 以及端口,例如: `http://google.com:80)。
这是为了防止你,例如,向你的竞争对手网站发请求,注销你的用户在对方网站的账号(这不好!)。这个问题牵扯到 <script>标记虽然有点意外,但如果实现了 <code>crossorigin,你只要加一个 handler 到 <code>window.onerror 事件上,就能在看控制台上看到一些警告信息,提示你引入了一个不该引入的外站脚本。在安全的浏览器下,<em>除非你指定 <code>crossorigin 属性,不然加载外站脚本不会出错。</script></p> <p><code>crossorgin</code> 不是一个神奇的安全手段,它所做的只是让浏览器启用正常的 CORS 访问检查,发起一个 <code>OPTIONS</code> 请求并检查 <code>Access-Control</code> header。</p> <h3 id="code-document-currentScript-code"><code>document.currentScript</code></h3> <p>IE 不支持的一个新奇的东西是个叫做 <code>document.currentScript</code> 的属性。它指向当前正在被执行的脚本。如果你想要从你嵌入的 <script>标记中拿一些属性来用,它会非常有用。我个人非常高兴它还没有被完全支持,否则它会让我们在一部分工作中渴望嵌入更复杂的代码。</script>
onafterscriptexecute
?!
这个超没用,因为它只被 Firefox 支持。使用 onbeforescriptexecute
能让你绑定事件到每一个脚本的执行前和执行后,这很酷。
如果你对这个感到好奇,你可以研究下。event 对象包含一个被执行的脚本的引用,而 before
事件能通过 perventDefault()
取消脚本的执行。
for
/ event
到今天, HTML5 规范包含了一个很少见的,以前是 IE 特殊的方法来绑一段代码到一个事件。你应该能向下面这样让一段代码不被执行直到页面加载完成:
<script for="window" event="onload"> alert("Hi!") </script>
这段代码在 Chrome 或者 Firefox 下不能实际工作,但是它依然能够在 IE 下工作。
NOSCRIPT
如同你父母一样,很难相信 JavaScript 也曾经年少过。曾经有过这样一段时间你不能确定是否一个浏览器支持 JavaScript。更糟的是,你甚至不能确定那个浏览器能识别 script
标记。而如果一个浏览器不能识别标记,它应该会将它渲染成一个 inline 元素,意味着你所有 JavaScript 代码会被作为文本渲染在页面上!
幸运地是,规范已经能足够有效地避免这个情况发生,你只需要将你的代码包在 HTML 注释里,那些不支持脚本的浏览器会把下面的文本当做注释:
<script> <!-- to hide script contents from old browsers // You would probably be pasting a ‘rollover’ script // you got from hotscripts.net here // end hiding contents from old browsers --> </script>
当然,像很多事情一样,XHTML将这变得更糟。XML用特殊的方法来转义可能包含结束标记的内容,这是 CDATA
的来历:
<script> //<![CDATA[ // Is this the right incantation to get this to pass // the XHTML validator? //]]> </script>
像上面这样写,你的代码可以是一个规范的 XHTML。它对实际功能没有什么影响,但是它对你作为一个 Web 开发者的荣誉也许很重要(现在这个时代,谁还用 XHTML 啊——译者注)。
浏览器也包含一个有用的方法来让你把那些不支持 JavaScript 人赶走,通过 noscript
标记。<noscript></noscript>
标记里的内容只有浏览器不支持脚本的时候才会被渲染出来:
<noscript> Please use Internet Explorer 5.5 or above. </noscript> <script> exploitInternetExplorer0Day(); </script>
如果你有敏锐的观察力,你会意识到 noscript
不接受 type
参数,这使得那些使用别的 type
类型的脚本的页面上如果出现 noscript
会显得有点歧义。noscript
实际行为在各个浏览器下有所不同。
<script>标记和 <code>innerHTML</script></h3>
<p>通过 DOM 动态添加到页面上的 <script>标记会被浏览器执行:</script></p><pre class='brush:php;toolbar:false;'>var myScript = document.createElement(&amp;#39;script&amp;#39;);
myScript.textContent = &amp;#39;alert(&quot;✋&quot;)&amp;#39;;
document.head.appendChild(myScript);</pre><p>通过 <code>innerHTML</code> 动态添加到页面上的 <script>标记则不会被执行:</script>document.head.innerHTML += '<script>alert("✋")</script>';
为什么会是这样的原因不是很确定,但是它解决了一个小问题:“是否有一个办法让一个 <script>标记在 Chrome 代码检查器中显示但不实际执行?”你可以利用这个来对你的同事做恶作剧。</script>
The above is the detailed content of Essential knowledge for WEB programmers about the tag. For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment