简体   繁体   中英

Check is external Javascript has changed or not

Here is my code which might not be the best solution of my problem, and my goal is to check the external script ( script.js ) every 2 seconds if it's code has changed. If it is changed, then execute it.

function connectLoader(retval) {
    console.log('Executing...');
    var old = document.getElementById("EPMagic");
    if (old !== null) {
      old.outerHTML = "";
      delete old; 
    }

    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement('script');
    script.setAttribute('id','EPMagic');
    script.setAttribute('type','text/javascript');
    script.setAttribute('src','http://server.com/script.js');
    head.appendChild(script);
}
setInterval('connectLoader()',2000);

The problem is that /script.js is still executed even if it is not being changed. The code on /script.js is simply alert('Execute');

Use setAttribue to set the attributes values:

var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','loadScript');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.ip/script.js');
head.appendChild(script);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM