I am beginner in javascript and has this problem can someone please explain what's the reason behind it.
Problem:
js.onload and js.error both getting called when script has error...when i am doing this js.onload function get called even when script has error....but if script doesn't has any error .onerror function is not being called..so problem is only with js.onload function
const loadScript1 = (src,func)=>{
let js = document.createElement("script");
js.src = src; //setting src attribute
js.onload = func(null,src);
js.onerror = func(new Error("Error in Script: "),src) //this function get executed when script js has error while loading
document.body.append(js);}
but Somehow if i declare a function and then calling func function inside it it solves the problem for example
this is working:
const loadScript1 = (src,func)=>{
let js = document.createElement("script");
js.src = src;
js.onload = function(){func(null,src);}
js.onerror = func(new Error("Error in Script: "),src) //this function get executed when script js has error while loading
document.body.append(js);}
can someone please explain Why????
This is full code:
const loadScript1 = (src,func)=>{
let js = document.createElement("script");
js.src = src; //setting src attribute
js.onload = func(null,src);
js.onerror = func(new Error("Error in Script: "),src) //this function get executed when script js has error while loading
document.body.append(js);
}
const loadedsc1 = (error,scrpt)=>{
if(error){
console.log(error+scrpt);
return;
}
alert("script loaded : "+scrpt);
}
//invalid script
loadScript1("https://cdn.jxxsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js",loadedsc1);