首页 > 解决方案 > JavaScript如何等待另一个java脚本首先被解析

问题描述

我遇到了异步 java 脚本的问题。这是我的html

<html>
   <head>
       <script src="/headScript.js"></script>
   </head>
  <body>
      <div id="inner_id" class="sample"> </div>
      ...
      <script src="/anOtherScript.js"></script>
  </body>
</html>

/headScript.js

  $(document).ready(function () {
  var target=$('#inner_id'); 
    $.ajax({                                                                 
        method: 'GET',
        url: '/example',
        success: function (result) {
                var el= document.createElement('span');
                el.id="new_element";              
                el.setAttribute('name', 'element');
                el.setAttribute('content', result);
                target.append(el)
        }
    });
  });

/anOtherScript.js

 $(document).ready(function () {
   console.log($('#new_element));
 });

来自标头的脚本创建了新的 div,但似乎这两个脚本正在异步运行,并且在控制台上我得到了未定义。有什么方法可以让 (anOtherScript) 等待第一个先解决?

标签: javascripthtmljquery

解决方案


发生这种情况是因为anOtherScript.js在您将其加载到 html 之后立即执行 - 这意味着立即执行。但是,您只能在从API#new_element获得响应后创建元素。example

要解决这个问题:确保 中的代码在 中的代码之后anOtherScript.js运行headScript.js

将所有anOtherScript.js内容放在一个函数中

const anotherScript = () => {
    $(document).ready(function () {
        console.log($(`#new_element`))
    });
}

然后从文件的success回调中调用这个函数headScript.js

success: function (result) {
                var el= document.createElement('span');
                el.id="new_element";              
                el.setAttribute('name', 'element');
                el.setAttribute('content', result);
                target.append(el)
                anotherScript();
        }

推荐阅读