当前位置:网站首页>The difference between script in head and body

The difference between script in head and body

2022-06-23 02:22:00 User 1349575

The loading order is different ,html It is loaded from top to bottom . If the network speed is slow js Code placed in body Users at the bottom will see the structure of the web page first , etc. js The special effect will not appear until the loading is completed .

difference : stay HTML body In section JavaScript It will be executed when the page is loaded . stay HTML head In section JavaScripts Will be executed when called , But preload the home page and the rest of the code .

1. JavaScript Where should I put it

head Script in section :

Scripts that need to be called to execute or scripts triggered by events to execute are placed in HTML Of head In the part . When you put the script in head In part , This ensures that the script is loaded before any call , This makes the code more powerful ; For example, yes. *.js Early invocation of files . That is to say, put the code in <head> When the page is loaded , The code is loaded at the same time , you are here <body> There is no need to load code when calling the , The speed increases , This difference is invisible in small programs , When running large and complex programs , You can see .

body Script in section :

The script that executes immediately when the page is loaded is placed in HTML Of body part . Put it in body Part of the script is usually used to generate the content of the page .

body and head Some can have scripts at the same time :

You can put countless scripts in the file , So your file can be found in body and head Some scripts exist at the same time .

2. If you put javascript Put it in head Words in Li , Is parsed first , But this time body Not resolved yet .

( routine html The structure is head before ,body After ) If head Of js The code needs to pass in a parameter ( stay body When calling this method, middle note , Parameters will be passed in ), And you need to call this parameter for a series of operations , Then you will definitely report an error at this time , Because the parameter of the function is undefined (undefined).

3. from JavaScript Consider the direction of page download performance

Because the script will block the download of other resources ( Such as pictures, etc. ) And page rendering , Until the script is completely downloaded and executed , The rendering of the page will continue , Therefore, it is recommended that all <script> The label should be placed as far as possible <body> The bottom of the label , To minimize the impact on the whole page download .

原网站

版权声明
本文为[User 1349575]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202081439110237.html