簡體   English   中英

jQuery在依賴於jquery的腳本之前加載,但后者仍顯示“未定義$”

[英]Jquery loaded before the jquery-dependent script, but the latter still says “$ is not defined”

在我的HTML頁面上,可以通過以下方式加載JS文件:

<script id="jjquery"></script>
<script id="jscookie"></script>
<script id="winx"></script>

<script>
(function(){
  if(screen.width > 479) 
    document.querySelector("#jjquery").setAttribute("src", "/js/jquery-3.3.1.min.js");
    document.querySelector("#jscookie").setAttribute("src", "/js/jscookie.js");
    document.querySelector("#winx").setAttribute("src", "/js/winx.js");
}());
</script>

基本上,我使用此答案中描述的方法僅從特定的屏幕分辨率開始加載某些腳本。 但是,依賴於jquery的三個腳本中的第三個腳本無法正常工作,並表示$ is not defined 即使我在控制台中輸入$ ,它也會返回正常響應。 而且,當我在HTML輸出中看到腳本的順序時,很顯然jquery在其他兩個腳本之前被加載。 這里可能是什么問題?

PS如果我只是正常地加載腳本而不進行分辨率檢查,那么一切都可以正常工作。

問題在於腳本是異步加載的,因此代碼的順序無關緊要。

您可以看到有關如何正確導入腳本的MDN示例

在您的情況下,如果某些腳本依賴於jquery,則可以創建一個onLoadJquery函數並將其附加為腳本的onload屬性,此函數將在導入后執行。

<script>
(function(){
  if(screen.width > 479) { 
    // add the callback that will be executed once jquery is loaded
    document.querySelector("#jjquery").addEventListener("load", onLoadJquery);
    document.querySelector("#jjquery").setAttribute("src", "/js/jquery-3.3.1.min.js");
    document.querySelector("#jscookie").setAttribute("src", "/js/jscookie.js");

  }

  function onLoadJquery() {
    // safely import the rest of the scripts
    document.querySelector("#winx").setAttribute("src", "/js/winx.js");
  }
}());
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM