title: How to know if a JavaScript (script) was loaded?
body: <p>I try to write a JavaScript function that loads a js script (<code>src</code>) and performs some callback when the script is loaded.</p>
  
  <p>I also look if a script with the same <code>src</code> already exists.</p>
  
  <p>My problem is that if the script already loaded, the callback will not be performed. That is NOK.  </p>
  
  <p><strong>How to know if the script was already loaded?</strong></p>
  
  <pre><code>importScript: (function (head) {
  
      function loadError(error) {
          throw new URIError("The script " + 
                              error.target.src + " is not accessible.");}
  
      return function (url, callback) {
          var existingScript = document.querySelectorAll("script[src='" + 
                               url + "']");
          var isNewScript = (existingScript.length == 0);
          var script;
          if (isNewScript) {
              script = document.createElement("script")
              script.type = "text/javascript";
          }
          else {
              script = existingScript[0];
          }
          script.onerror = loadError;
          if (script.readyState) { //IE
              script.onreadystatechange = function () {
                  if (script.readyState == "loaded" || 
                      script.readyState == "complete") {
                      script.onreadystatechange = null;
                      if (callback) {
                          callback(); }
                  }
              };
          } else { // others than IE
              script.onload = callback; }
  
          if (isNewScript) {
              script.src = url;
              head.appendChild(script); }
      }
  })(document.head || document.getElementsByTagName("head")[0])
  </code></pre>
  
  <p>As I understand, the <code>script.readyState == "loaded" || script.readyState == "complete"</code> could work <strong>only for IE</strong>, not for other browsers as well...</p>
  
  <p>Usage:</p>
  
  <pre><code>importScript("myScript1.js");
  importScript("myScript2.js", /* onload function: */ 
              function () { alert("The script has been OK loaded."); });
  </code></pre>