How do I use js to detect the existence of remote js files?
The
project uses a printing function that angularJS needs to develop, which requires a local installation of a program with two local js files available to access
in addition, I have globally added a js file, which will inject the above two js files into the head of dom, but I only want to inject the pages I need, and make sure that the two files have been loaded when the page loads and executes the logic.
can be injected into the head of dom to monitor onload onerror events
XmlHttpRequest to get the content, and then write dom
XmlHttpRequest file does not exist, handle the error report
(async function(){
try{
var src1 = 'http://localhost:8000/CLodopfuncs.js?priority=1';
var src2 = 'http://localhost:18000/CLodopfuncs.js?priority=0';
await Promise.all(import(src1),import(src2));
console.log('success');
}catch(e){
console.log('error');
}
})()
there are requirements for browsers
at present, when I get js, I create a script tag, insert it into head, and then give it an expiration time. If I don't get this js, after expiration, it means that js does not exist.
const getScript = (url, sid) => {
const head = document.getElementsByTagName('head')[0];
const script = document.createElement('script');
const timeout = 5000; //
let timer;
script.setAttribute('type', 'text/javascript');
script.setAttribute('charset', 'UTF-8');
script.setAttribute('src', url);
if (sid) {
script.setAttribute('id', sid);
}
const cleanup = () => {
if (script.parentNode) { script.parentNode.removeChild(script); }
if (timer) { clearTimeout(timer); }
};
head.appendChild(script);
return new Promise((resolve, reject) => {
//
const callbackFn = () => {
if (timer) { clearTimeout(timer); }
resolve();
};
script.onload = () => {
callbackFn();
};
if (timeout) {
timer = setTimeout(() => {
cleanup();
reject(new Error('timeout'));
}, timeout);
}
});
};
getScript('http://localhost:8000/CLodopfuncs.js?priority=1')
.then(()=>{
})
.catch(err=>{
console.log(err, 'js isn\'t exsit');
})