Home > Web Front-end > JS Tutorial > What is defer in javascript

What is defer in javascript

醉折花枝作酒筹
Release: 2023-01-07 11:44:41
Original
3348 people have browsed it

defer tells the browser that the Script segment contains code that does not need to be executed immediately, and is 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; the syntax "< ;script defer>js code".

What is defer in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Many people are already proficient in using Javascript, but when they see defer, they may not know what it is used for; many people have also encountered such a problem and need to directly execute and manipulate the DOM. The object's js always reports an error that the object cannot be found. As everyone knows, the reason is that the page has not been loaded yet, and the js operation object is still being downloaded. But many people don't know that adding the defer tag can easily solve this problem. The function of defer in

<script src="../CGI-bin/delscript.js" defer></script>
Copy after login

is to execute the script after the document is loaded, so as to avoid the problem of not finding the object --- a bit of a problem

<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

Adding defer means that the page is completely loaded. Then execute it, which is equivalent to window.onload, but is more flexible in application than window.onload!

defer is an "unsung hero" in the power 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.

Please note two points:

1. Do not call the document.write command in a defer-type script segment. Because document.write will produce direct output effects.

2. Moreover, do not include any global variables or functions to be 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

Latest Issues
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template