Script tag-----JavaScript sorting, review, sorting, interview questions

JavaScript

The author suddenly wants to sort out the JS I have learned. On the one hand, I can improve my own shortcomings. On the other hand, I also hope that people who read this article can point out my shortcomings. I would like to thank you for this. (Compiled based on the Little Red Book and my own ideas, and some related interview questions will also be added)

JS in HTML

1. <script>tag

Insertjavascript intohtml and mainly use the tagscript. This tag has 8 attributes

async: Optional attribute. Indicates that you can start downloading the script immediately, but cannot prevent other page actions. 只对外部文件有效
charset: Optional attribute. Use src to specify the code character set.
crossorigin: Optional attribute. Configure CROS settings for related requests.
defer: Optional attribute. It means that there is no problem in executing the script after the document parsing and display is completed. 只对外部脚本文件有效
integrity: Optional attribute. Allows verification of subresource integrity by comparing the received resource to the specified cryptographic signature
src: Optional attribute. Represents the external file to be executed
type: Optional attribute. Instead of language, it represents the content type (also called MIME type) of the scripting language in the code block.
language: Deprecated

src

scriptIf the tag uses the src attribute, you cannot use code in the tag. If both are provided, only the script will be downloaded and the code in the tag will be ignored. At the same time, the src attribute of script can be a complete url, and the resource pointed to by this url can be the same as the that contains it. >HTMLNot the same domain

<script src="https://www.somewhere.com/afile.js"></script>

At the same time, when the browser parses this resource, it will send a request to the path specified by the src attribute to obtain the resource. This request is not restricted by the browser's same-origin policy, but the returned and executed is restricted. At the same time, this request is still restricted by the parent page's protocol. . GETJavaScriptHTTP/HTTPS

defer

Delay script execution: After the defer attribute is added to the script element, the structure of the page will not be changed, so this script can be executed after the entire page is parsed. Setting this attribute will tell the browser to 立即下载脚本,但是最后执行脚本 multiple elements with the defer attribute set at the same time, according to The requirements of the specification should be implemented in order. Because not all browsers support the defer attribute, it is best to place the deferrable script at the bottom of the page. scriptHTML5

值得注意的是对于XHTML文档指定defer属性时应该写成defer="defer"

async(不推荐使用这个方法)

Execute script asynchronously: async is similar to defer in terms of changing the script execution method. Both attributes only apply to external script files. They will tell the browser to start downloading the file immediately. However, script files using async may not necessarily be executed in order, so使用async的脚本之间不能存在依赖关系, add the async attribute to the script. The purpose is to tell the browser that there is no need to wait for the script to be downloaded and executed before loading the page, and at the same time, there is no need to wait for the asynchronous script to be downloaded and executed before loading other scripts, so异步脚本不应该在加载期间修改DOM元素
值得注意的是对于XHTML文档指定defer属性时应该写成async="async"

动态加载脚本

Because JavaScript can use the DOM API, you can also load a specified script by adding a script element to the DOM. Just create the script element and add it to the DOM

let script = document.createElement(`script`);
script.src = 'gibberish.js';
document.head.appendChild(script);

After adding this to the DOM element, the request will not be sent before executing this code. Because the async attribute is added to the script element by default, but all browsers support the createElement() method, but not all browsers support async, so to unify the loading behavior of dynamic scripts, you can set it to synchronous load:

let script = document.createElement(`script`);
script.src = 'gibberish.js';
script.async = false;
document.head.appendChild(script);

But this method is also flawed, because the resources obtained in this way are invisible to the browser preloader, which will seriously affect their priority in the resource acquisition queue. So to let the preloader know about these request files, you can display a declaration in the head of the document:

<link rel="preload" href="gibberish.js">

2. <noscript>tag

To solve the problem of early browsers not supporting JavaScript, a graceful downgrade solution is needed, so noscript appears to solve the problem of not supporting . In the following two cases, the browser will display the content contained in , except element can contain any HTML element that can appear in . The JavaScriptProvide alternative content. It has its own uses for browsers that disableJavaScript
noscript元bodyscriptnoscript

  1. The browser does not support scripts
  2. Browser support for scripts is turned off

3. 面试题

SimplificationsrcGivehrefDivision
  1. src is used to replace the current element, href is used to establish a relationship between the current document and the referenced resource.
  2. src is the abbreviation of source, pointing to the location of an external resource. The content pointed to will be embedded in the document at the location of the current tag; when requesting src resources The resources it points to will be downloaded and applied to the document, such as jsscripts, imgimages and frame elements a>
  3. href is the abbreviation ofHypertext Reference, which points to the location of the network resource and establishes a link to the current element (anchor) or current document (link),

If we add <link href="common.css" rel="stylesheet"/> to the document, the browser will recognize the document as css文件, download the resources in parallel and will not stop processing the current document processing. This is why it is recommended to use the link method to loadcss instead of using the @import method

<script src ="js.js"></script> When the browser parses this element, it will suspend the downloading and processing of other resources until the resource is loaded, compiled, and executed. The same is true for elements such as pictures and frames, which is similar to embedding the pointed resource into the current within the label. This is why thejsscript is placed at the bottom instead of the head

Will the position of script affect the first screen display time?
  1. In the process of parsing HTML to generateDOM, js files are downloaded in parallel and do not need to be processed DOM script node. Therefore, the position of script does not affect the start time of the first screen display.
  2. Browser parsing HTML is a top-down linear process,scriptas part of HTML also follows this principle. Therefore, script will be delayed by DomContentLoad and only part of the above-the-fold content will be displayed, thus affecting the completion time of the above-the-fold display
What is the difference between script tagdefer and async
  1. script: HTML parsing is paused, download JS, execute JS, and continue to parse HTML.
  2. defer: HTML continues to be parsed and downloaded in parallelJS, HTML will be executed after parsingJS (no need to put script in After the body, we put the js script in the head<script defer>It will be better to load the js script in parallel)
  3. async: HTML continues to be parsed, downloaded in parallelJS, executedJS (executed immediately after loading, 谁先加载完成谁先执行), Continue parsing HTML. Execute immediately after loading, which causes the scripts under the async attribute to be out of order. This does not apply to situations where script has sequential dependencies

Note: JS is single-threaded, JS parsing thread and DOM parsing thread share the same thread, < /span>JS执行和HTML解析是互斥的, loading resources can be done in parallel

prefetchWhat are anddns-prefetch respectively
preloadandprefetch
  1. preloadResources are used on the current page and will be loaded first. You can indicate which resources are needed immediately after the page is loaded. The browser preloads before the main rendering mechanism intervenes. This mechanism allows resources to be loaded and available earlier, and is less likely to block the initial rendering of the page. thereby improving performance. needas指定资源类型
  2. prefetchResources are used on future pages and loaded when idle. It uses browser idle time to download or prefetch documents that the user is likely to access in the near future.
<head>
  <!-- 当前页面使用 -->
  <link rel="preload" href="style.css" as="style" />
  <link rel="preload" href="main.js" as="script" />

  <!-- 未来页面使用 提前加载 比如新闻详情页 -->
  <link rel="prefetch" href="other.js" as="script" />

  <!-- 当前页面 引用css -->
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <!-- 当前页面 引用js -->
  <script src="main.js" defer></script>
</body>

目前可用的属性类型如下:
audio: 音频文件。
document: 一个将要被嵌入到<frame><iframe>内部的HTML文档。
embed: 一个将要被嵌入到<embed>元素内部的资源。
fetch: 那些将要通过fetch和XHR请求来获取的资源,比如一个ArrayBuffer或JSON文件。
font: 字体文件。
image: 图片文件。
object: 一个将会被嵌入到<embed>元素内的文件。
script: JavaScript文件。
style: 样式表。
track: WebVTT文件。
worker: 一个JavaScript的web worker或shared worker。
video: 视频文件。
dns-preftchandpreconnect
  1. dns-pretchDNS prequery
  2. preconnectDNS preconnect

Reduce DNS resolution time with prequeries and preconnects

<head>
  <!-- 针对未来页面提前解析:提高打开速度 -->
  <link rel="dns-pretch" href="https://font.static.com" />
  <link rel="preconnect" href="https://font.static.com" crossorigin />
</head>

おすすめ

転載: blog.csdn.net/WDJ_webDeveloper/article/details/134220764