首頁  >  文章  >  web前端  >  使用腳本標籤同步載入檔案時要避免的常見錯誤

使用腳本標籤同步載入檔案時要避免的常見錯誤

WBOY
WBOY原創
2024-07-20 12:44:471089瀏覽

您可能認為同步載入腳本會使腳本下載後執行下一行程式碼,對嗎?但這並不是同步載入 javascript 檔案的含義。當您比較載入特定檔案的非同步、同步和延遲策略時,就會出現混亂。

更多關於以非同步、同步、延遲方式載入 javascript 檔案的資訊請參閱文章末。

這裡我們先討論程式碼執行。若要在腳本成功下載後執行程式碼行,可以在 script 標籤上使用 onload 屬性。請參考下面的程式碼片段:

<html>

<head>
    <title>Sync Script Tag</title>
</head>

<body>
    <h1>Load script sync.</h1>
</body>
<script>
    function  afterLoad() {        
        console.log('script loaded successfully.') // executes after script has loaded   
    }    
    function  sync_load()  {        
        console.log('sync_load...')         
        var  s  =  document.createElement('script');        
        s.type  =  'text/javascript';        
        s.async  =  false; // load synchronously       
        s.onload  =  afterLoad;        
        s.src  =  "https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js";        
        var  x  =  document.getElementsByTagName('script')[0];        
        x.parentNode.insertBefore(s,  x);            
    }    
    console.log('JS entry')     
    sync_load();    
    console.log('next tick') // this executes before after_load 
</script>

</html>

輸出:

Common mistake to avoid while loading a file synchronously using script tag

現在,回到非同步、同步、延遲策略,請透過stackoverflow參考下圖:

Common mistake to avoid while loading a file synchronously using script tag

在這種情況下,非同步與同步之間的差異在解析 HTML 檔案時發揮作用。記住這一點!

編碼愉快✨

以上是使用腳本標籤同步載入檔案時要避免的常見錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:我需要幫助下一篇:我需要幫助