r/learnjavascript • u/DeliciousResearch872 • Feb 07 '26
Promisification question
Can anyone explain "callback(null, script)" here?
function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(null, script);
script.onerror = () => callback(new Error(`Script load error for ${src}`));
document.head.append(script);
}
// usage:
// loadScript('path/script.js', (err, script) => {...})
0
Upvotes
View all comments
Show parent comment
4
u/senocular Feb 07 '26
You're not getting an error from onerror, only an Event. And its not even an ErrorEvent, just a normal event with the type "error" without any additional error information. The way the callback is being used, its providing a custom error as the error since no other error is available.
Otherwise, if you had a method which provided an error argument, you could assign the callback directly to that method property. For example if onerror got called with a native error, you could instead say
Assuming you were fine with all of the information in that error getting to your callers.