0

I am loading javascript dynamically and accessing its variable. I checked the second answer from this question and the following code works beautifully.

include = function (url, fn) {
    var e = document.createElement("script");
    e.onload = fn;
    e.src = url;
    e.async=true;
    document.getElementsByTagName("head")[0].appendChild(e);
};

include("test.js",function(){
    console.log(foo);
});

QUESTION: I want to have a onFailure callback function as well that allows me to process code in case

  • The internet is down.
  • The filename is not accessible (eg: incorrect path)

Will appreciate if someone can guide me to the right direction. Thanks

3
  • 1
    The MDN page for the HTMLScriptElement has a good example which you can build off. Commented Feb 9, 2016 at 6:16
  • Yeah that example works fine for me. Neat solution. Thanks Commented Feb 9, 2016 at 6:50
  • Added it as an answer then. Commented Feb 9, 2016 at 7:26

2 Answers 2

1

The MDN page for the HTMLScriptElement has a good example which you can build off.

function loadError (oError) {
  throw new URIError("The script " + oError.target.src + " is not accessible.");
}

function importScript (sSrc, fOnload) {
  var oScript = document.createElement("script");
  oScript.type = "text\/javascript";
  oScript.onerror = loadError;
  if (fOnload) { oScript.onload = fOnload; }
  document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
  oScript.src = sSrc;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think the simplest solution is to actually use an XMLHttpRequest. This gives you access to the status of the request after it completes, where the "load" event does not. For simplicity, I'll illustrate with jQuery, but this can be written in vanilla javascript as well.

$.ajax({
    url:"myfile.js",
    method:"GET",
    dataType:"html",
    success: function(data, status, jqxhr) {
                 console.log("It worked");

                 // This can be very dangerous. Make sure you trust script source.
                 var newScript = $("<script>").html(data);
                 $('body').append(newScript);
             },
    error: function(jqxhr, status, error) {
               console.log("Oh no!");
           }
});

More on the jQuery ajax request here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.