Loading Javascript Dynamically and how to check if the script exists

后端 未结 9 553

I am using the following technique to load up Javascript dynamically:

var script = document.createElement(\"script\");
script.type = \"text/javascript\";
scr         


        
9条回答
  •  离开以前
    2020-12-01 17:03

    Recently in my vue.js project I tried to something like this, I am using es6 so make sure you have the setup. This is just vanilla javascript, so this should run without any issue.

    function handleLoad() {
      // on scirpt loaded logic goes here
      ...
    };
    
    function handleLoadError(yourScript) {
      // on scirpt loading error logic goes here
      ...
    
      // remove the script element from DOM if it has some error
      document.head.removeChild(yourScript);
    };
    
    function generatePan(token) {
      // if script does not exist only then append script to DOM
      if (!document.getElementById('your-script')) {
        const yourScript = document.createElement('script');
        yourScript.setAttribute('src', 'https://your-script.js');
        yourScript.setAttribute('id', 'your-script');
        yourScript.async = true;
        yourScript.addEventListener('load', () => handleLoad(), false);
        yourScript.addEventListener('error', () => handleLoadError(yourScript), false);
    
        document.head.appendChild(yourScript);
      } else {
        // runs if script is already loaded DOM
        handleLoad();
      }
    };
    

    Also, please check this link, even this may help.

提交回复
热议问题