Martyn Ball
Martyn Ball

Reputation: 4885

script.onerror not throwing an error when url is incorrect

I have got the code below which should throw and error if the URL is incorrect. However nothing is actually happening, even though the URL is defiantly incorrect.

function loadApi() {
    var script = document.createElement('script');
    script.src = 'https://maps.googleapiss.com/maps/api/js?key={key}&libraries=geometry';
    script.onerror = function() {
      exit('MarvMap: Unable to load Google Map API, please check the URL.');
    };
    script.onload = function () {
      document.head.appendChild(this);
    };
  }
function exit(message = 'Exiting MarvMap') {
    throw new Error(message);
  }

Upvotes: 1

Views: 104

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074535

The script isn't loaded until/unless you append the element to the DOM. If you do that, you see the error:

function loadApi() {
    var script = document.createElement('script');
    script.onerror = function() {
        exit('MarvMap: Unable to load Google Map API, please check the URL.');
    };
    script.onload = function () {
        console.log("Loaded");
    };
    script.src = 'https://maps.googleapiss.com/maps/api/js?key={key}&libraries=geometry';
    document.head.appendChild(script);
}

(I also habitually hook the handlers before setting the src, because it matters with images. But not with scripts.)

Upvotes: 2

Related Questions