一般載入js 我們用到 script tag
<script src="demo.js"></script>
而在 HTML 4, HTML 5 分別新增了 defer 與 async,用來更好的控制 script 的載入順序,其中優點在於:
- 以避免 DOM 解析,因為仍有其他 JS 檔案在下載,造成卡住(白畫面)
- 讓必要的 JS 能有順序的下載執行,避免執行序錯亂造成程式錯誤
使用情境依需由而定,沒有固定。
async
白話說,讓 JS 進行非同步加載,下載完,停止DOM解析,並立即執行該JS,執行完在往下繼續DOM解析。
<script src="demo.js" async></script>
使用時機:
針對有執行順序 or 必要優先載入的JS,使用時須注意JS 的擺放順序,以避免JS執行錯誤。
defer
白話說,讓 JS 進行同步加載,下載時並不會中斷DOM解析,會等 DOM解析完成後才執行。
<script src="demo.js" defer></script>
使用時機:
針對沒有執行順序 or 非必要 or 可延後載入的JS。
async 與 defer 兩個都沒有時
當script tag 沒有下 async 與 defer 時,進入頁面會依舊對 DOM 開始解析,當JS有下載完成時,停止DOM解析,並先執行下載完的 JS ,執行完後,再繼續DOM解析。
gateio
After reading your article, it reminded me of some things about gate io that I studied before. The content is similar to yours, but your thinking is very special, which gave me a different idea. Thank you. But I still have some questions I want to ask you, I will always pay attention. Thanks.
Binance
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/zh-CN/register?ref=V2H9AFPY
Зарегистрируйтесь, чтобы получить 100 USDT
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://www.binance.com/ru-UA/register?ref=V2H9AFPY
Cryptocurrency Prices
Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.
gate io borsası
Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.
Sign Up
I have read your article carefully and I agree with you very much. This has provided a great help for my thesis writing, and I will seriously improve it. However, I don’t know much about a certain place. Can you help me?