Home > Web Front-end > JS Tutorial > An example of the role of JS script defer

An example of the role of JS script defer

PHPz
Release: 2018-09-30 17:02:18
forward
1298 people have browsed it

The function of defer is to execute the script after the document is loaded, so as to avoid the problem of not finding the object. There is a good example below, and interested friends can refer to it.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<script src="../cgi-bin/delscript.js" defer></script>

中的defer作用是文档加载完毕了再执行脚本,这样回避免找不到对象的问题---有点问题

<button id="myButton" onclick="alert(&#39;ok&#39;)">test</button>

<script>

myButton.click();

</script>

<script>

myButton.click();

</script>

<button id="myButton" onclick="alert(&#39;ok&#39;)">test</button>

<script defer>

function document.body.onload() {

alert(document.body.offsetHeight);

}

</script>

Copy after login

Added defer means that it will be executed after the page is completely loaded, which is equivalent to window.onload, but is more flexible than window.onload in application!

defer is an "unsung hero" among the powerful functions of scripting programs. It tells the browser that the Script segment contains code that does not need to be executed immediately, and, used in conjunction with the SRC attribute, it can also cause these scripts to be downloaded in the background, and the content in the foreground is displayed to the user normally.
But execute the script after the document is loaded

Finally, please note two points:

1. Do not call the document.write command in a defer-type script segment, because document.write Will produce a direct output effect.
2. Moreover, do not include any global variables or functions used by the immediate execution script in the defer script segment.

A common way to optimize performance is to set the "defer" attribute in the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template