0

The Google javascript API client library script is loaded in the section like this:

<script src="https://apis.google.com/js/client.js?onload=loadBodies" type="text/javascript"></script>

The method specified in the onload parameter is called when the API code has loaded. Is it guaranteed that this will also be after the DOM has finished loading? My onload method needs to find an element by ID and modify it using data obtained from the Google API, and I'm worried about whether I can count on the element being available at the time the method is called. jsjs

isomeme
  • 451
  • 3
  • 12

1 Answers1

1

The JS Client loads asynchronously independent of the DOM load, so there is no guarantee the DOM will be ready when the JS Client has finished loading. You can wait for DOM load to start loading the JS Client, but for best performance I recommend using a window.onload callback and a JS Client onload callback, and look for your element in whichever fires second.

Brendan
  • 56
  • 3
  • What's the best way to determine which is running second? The first idea that comes to mind is simply flipping a global boolean to indicate "someone already ran", and doing the dom work in whichever method finds the boolean already true. Is there a cleaner/better way? – isomeme Feb 26 '13 at 19:08
  • For the record, that approach worked fine, so far as I can tell. It's always hard to be sure with race conditions. – isomeme Feb 28 '13 at 00:31
  • 1
    @isomeme, your approach should work fine. You don't need to worry about race conditions because JavaScript is single threaded. The second time it runs, you can be sure that the first run is already complete. Having said that, my preferred approach is to re-write the callback function when it first runs, and then do the useful work on the second run. This way, we don't need to manage a global variable for this single purpose. Here's an example: http://jsfiddle.net/MkpX4/ – Johnny Oshika Jul 24 '13 at 22:26