简体   繁体   中英

Dynamically loaded javascript starts executing before loading js file fully

I am dynamically adding scripts with the function below:

function loadScript(scriptUrl) {
    const body = this.document.getElementsByTagName('body')[0];
    const script = this.document.createElement('script');
    script.id = elmName;
    script.src = `${scriptUrl}`;
    script.async = false;
    script.defer = true;
    script.onload = () => {console.log("LADEDED: " + scriptUrl);}
    body.appendChild(script);
}

The loaded scripts call functions that are defined after them. They work well when i normally add to html. But if i add scripts dynamically with the above function, it gives undefined error for calling functions defined after the call.

With the logging on dynamic script load, i saw that (dynamically added) scripts starts executing before their file is fully loaded. Thus the undefined error comes before "LOADED:" log.

I tried to turn async loading off, and defer. Still same problem.

EDIT:

Defer works now. Scripts load in order. Yet the undefined errors continues.

jQuery(...).hover3d is not a function

hover3d is defined at the same file the error occurs.

I explained everything in comments so read it first

// make normal function to arrow function according es6 syntax 
const loadScript = (URL, elemName) => {
      // return a promise to handle time error
      return new Promise((res, rej) => {
        // try and catch block to handle any kind of err
        try {
          // create a script element
          const script = document.createElement("script");
          // a simple way to set attributes according to me
          Object.assign(script, {
            id: elemName,
            src: URL,
          });
          // whenever the script load this function will fire and resolve promise until .then will not fire so add function never call before.
          script.addEventListener("load", () => res(`Loaded: ${URL}`));
          // append script into body
          document.body.appendChild(script);
        } catch (err) {
          // reject promise with err
          rej(err);
        }
      });
    };
    loadScript("./math.js", "mathScript").then(() => {
      // call add function from another script
      add();
    });

I am not 100% sure that this will work Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM