0

I'm trying to write a promise base function that load-scripts. this is my code :

export const loadScript = ({ url,  id }) => {      
  return new Promise((resolve, reject) => {
    try {
      const scriptTag = document.createElement("script");
      scriptTag.src = url;
      scriptTag.id = id;
      scriptTag.onerror = (e) => {
        console.log("failed", e);
        reject("failed");
      };          
      scriptTag.onload = (e) => {
        console.log("done", e);
        resolve("done");
      };          
       document.body.appendChild(scriptTag);
    } catch (error) {
      reject("fail");
    }
  });
};

it works fine but when I tried to test my code and passed a wrong url to the function neither onerror nor catch was called,and it just called the onload callback.

how can I get when the script doesn't exist?

morteza
  • 718
  • 1
  • 9
  • 14
  • which wrong url did you try? – henok Jul 30 '20 at 15:07
  • Does this answer your question? [How to tell if a – James Jul 30 '20 at 15:08

0 Answers0