How can I load external javascript files using AJAX and know that loading has failed? -


i have written function takes array of url strings first argument , tries use them load external script. allows me link multiple sources in case 1 mirror down.

function loadscript(scripts, name, index) {   //convert single string array - not effective easy   if(!(scripts instanceof array))     scripts = [scripts];   //use first script src if no name defined   if(name==null) {     name = scripts[0];   }   //default index 0   if(index==null)     index = 0;   //in case wrong index provided   if(index>=scripts.length)     throw new error("aray index out of bounds.");    //create request   var req = new xmlhttprequest();   req.open("get", scripts[index]);   //execute response text on success    req.onload = function() {     scriptfromstring(this.responsetext);   }   //iterate on error   req.onerror = function() {     if(index+1<scripts.length) {       loadscript(scripts, name, index);     }     else {       throw new error("all sources failed '"+name+"'.");     }   }   req.send(); } 

the problem annoying cors breaking down design:

cross-origin request blocked: same origin policy disallows reading remote resource @ https://[...].js. can fixed moving resource same domain or enabling cors. 

how can overcome this? why loading script src ok, ajax request throws errors?

instead of trying js file xhr query, why not load through dom creating new <script> element , setting src= attribute file you're trying load? since it's dom, loading across domains legal.

function loadscript(scripts, name, index) {      //convert single string array - not effective easy     if (!(scripts instanceof array)) scripts = [scripts];      //use first script src if no name defined     if (!name) name = scripts[0];      //default index 0     if (!index) index = 0;      //in case wrong index provided     if (index >= scripts.length) throw "array index out of bounds.";      //create request     var include = document.createelement('script');     with(include) {         type = "text/javascript";         src = scripts[index];         onload = function () {             return;         };         onerror = function () {             if (++index < scripts.length) {                 loadscript(scripts, name, index);             } else {                 throw "all sources failed '" + name + "'.";             }         };     }     document.head.appendchild(include); } 

(not sure you're doing name argument / variable, left alone. might ought work on whatever logic intended employ name.)


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -