how to load the google maps API only when my app is navigator.onLine?

250 Views Asked by At

How can I add some javascript which only loads the google maps api:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

when my app is online (navigator.onLine == true)?

1

There are 1 best solutions below

0
Chad Killingsworth On BEST ANSWER

Use dynamic script insertion:

if(navigator.onLine) {
  var script = document.createElement('script');
  //You must use the callback parameter when loading the script asynchronously
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize';
  var scripts = document.getElementsByTagName('script');
  scripts[0].parentNode.insertBefore(script, scripts[0]);
}

function initialize() {
  //initialize map here
}

See the Asynchronous Loading topic in the Google Maps API v3 Documentation.

You might also be interested in Google Maps API v3: Developing for Mobile Devices