页面加载完成后,如何加载新脚本?

时间:2019-02-05 15:16:27

标签: javascript

我有两个单独的脚本文件(script1.js,script2.js)。每个文件都定义了自己的函数/变量。为了简单起见,我将假定每个文件都包含一个单独的变量。因此文件将如下所示:

script1.js

var x = 2;

script2.js

var y = 2;

我正在使用index.html中的脚本:

index.html

<button onclick="change()">Change script</button>
<script id="file" src="script1.js"></script>
<script>
  function change() {
    var file = document.getElementById("file");
    if(file.src.slice(-10) == "script1.js") {
      file.src = "script2.js";
    } else {
      file.src = "script1.js";
    }
  }
</script>

但是,当我更改脚本的src属性时,加载的脚本不会更改。因此,即使在切换脚本之后,x的值仍为2,而y的值尚未定义。

页面加载完成后如何切换脚本?

3 个答案:

答案 0 :(得分:2)

不确定要完成的操作,但是就JavaScript的加载而言,您可以使用:

$("#id_of_button").click(function(){
$.getScript('helloworld.js', function() {
    //do whatever you want to accomplish here....
});

});

更多详细信息here

更好的方法可能是将相关代码保留在同一js文件中的单独函数中,并根据您的条件检查调用特定函数以覆盖逻辑。虽然我仍然不清楚您要达到的目标。我可以提出一些基于场景的想法来弄清楚吗?

答案 1 :(得分:1)

您必须创建一个新脚本才能加载它,问题是您还想保持脚本的位置。

因此,在此我举了一个示例,该示例将替换旧脚本并将新脚本插入相同位置。

阅读评论以了解其工作原理。

  function change() {
    var file = document.getElementById("file"); // get the script you want to change
    var newscript = document.createElement("script"); // create new script
    newscript.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" // set the new script src
    newscript.setAttribute("id","file"); // set the id to the same id as the old script
    newscript.type = 'text/javascript';
    file.parentNode.insertBefore(newscript, file); // insert the new script before the old one
    file.remove() // remove the old script
    
    var callback= function(){ // when the script has been loded then test and see if jquary is working now
      $("body").append("<p>Jq loaded</p>"); // no error then Jquary has been loaded
    }
    newscript.onreadystatechange = callback;
    newscript.onload = callback;
  
  }
<script id="file" src="script1.js"></script>
<button onclick="change()">Change script</button>

答案 2 :(得分:1)

您可以尝试以下操作:https://codepen.io/anon/pen/mvMZOR

HTML

<button type="button">Change script</button>
<script id="file" src="script1.js"></script>

JavaScript

var index = 1;
var scriptId = 'file';
var button = document.querySelector('button');

button.addEventListener('click', function() {
  // Remove the old script
  document.getElementById(scriptId).remove();
  // Create the new one
  var s = document.createElement('script');
  // Add the id you want, in this case "file"
  s.id = scriptId;
  // It will return "script1.js" or "script2.js" alternatively
  s.src = 'script' + (index++ % 2 + 1) + '.js'; 
  // Append your new script at the end of your body
  document.querySelector('body').append(s);
});
相关问题