4

Here's my code. It tries to load Leaflet library. When I turn crossDomain option to true, the error callback is not fired. When I turn the option to false, the error callback is fired, but it can't download the js, because it's crossdomain.

Why so hard? Is there any solution to this? There's an image placeholder instead of a web map (to not load it initially and save page loading time), and when user activates the map, the js should be loaded. But if it fails, I want to show a normal error message and a retry button.

$.ajax({
    url: 'http://code.leafletjs.com/leaflet-0.3.1/leaflet.js',
    success: start_map,
    error: show_map_error,
    dataType: 'script',
    crossDomain: true
});

update: I tried complete callback, it doesn't work either.

update2: the same applies to crossdomain $.getScript(...).fail(...).

culebrón
  • 34,265
  • 20
  • 72
  • 110

1 Answers1

6

Crossdomain and Ajax are really annoying every now and then. This is a JavaScript issue, and not just a jQuery issue.

Basically it is like this: When you turn off the cross domain functionality, the error will fire, because jQuery/JavaScript expects a same domain call. This is not the case, so it fails.

When you are doing a cross domain call, and so the crossDomain is set to true, you will not get into the error because of the cross domain limitations of JavaScript.

There are some solutions (or workarounds) for this.

First one, if you have access to the backend system you are calling, you can set (in my example PHP) headers to allow a cross domain call. (I assume you are requesting JSONP here?). When you do this, then JavaScript accepts the call, and no crossdomain tricks are needed.

header('Access-Control-Allow-Origin: http://domain1.com, http://domain2.com'); //whitelist

Look here: Cross domain xmlhttp

If you have no access to the backend, you will need to do a workaround, which is basically a timeout on the Ajax Call as the error functions will never fire. This workaround is however very dirty, and when there is a hiccup on the line, or the internet is slow, this timeout will fire.

$.ajax({
    url: 'http://code.leafletjs.com/leaflet-0.3.1/leaflet.js',
    success: start_map,
    error: show_map_error,
    timeout: 2000, // 2 seconds timeout before error function will be called
    dataType: 'script',
    crossDomain: true
});
Community
  • 1
  • 1
Rene Pot
  • 24,681
  • 7
  • 68
  • 92