r/learnjavascript • • 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

8 comments sorted by

View all comments

Show parent comment

4

u/senocular Feb 07 '26

The callback can be anything. loadScript is simply following the error-first callback style popularized by Node. This uses a single callback for both success and error conditions where if there's an error, an Error object would appear as the first argument, and if not, the successfully loaded data (if any) would be provided in the second argument with a null first argument. To be able to adhere to this format, this custom new Error is needed in the error case because one isn't provided by the native APIs.