首页 > 解决方案 > 仅在刷新后使用 JS 或 JQ 动态加载的脚本

问题描述

当我尝试使用 JS 或 JQ 加载脚本时,我几乎没有问题。我已经添加了主体底部的 jquery 和它之后的另一个脚本。从这个脚本中,我又加载了一个脚本,但有时我需要刷新页面才能使其正常工作。

我试过用JS:

$(window).on("load", function() {
    var script = document.createElement("script");
    script.src = "scriptPath.js";
    script.async = false; // the result is same with true
    script.onload = function () {
      //do something here
    };
    document.body.appendChild(script);
 });

我试过 JQ:

  $(window).on("load", function() {
    $.getScript( "scriptPath.js" )
      .done(function() {
        //do something here
      })
      .fail(function() {
        //do something here
    });
  });

我也尝试在 head 标签中加载脚本,但结果是一样的。任何建议可能是什么原因?

标签: javascript

解决方案


这是有效的片段..

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>title</title>
</head>
<body>
    <div>
        BOO
    </div>
    <script>
        (function () {
            var script = document.createElement("script");
            script.src = "2.js";
            script.async = false; // the result is same with true
            script.onload = function () {
                console.log(booVar);
            };
            document.body.appendChild(script);
        })();
    </script>
</body>
</html>

2.js内容:

var booVar = 'booV';

请注意,在这种情况下,section 位于正文的末尾。如果将相同的脚本放在 ' 部分中,它将无法工作,因为此时 document.body 将为空。


推荐阅读