Question

I have a page where I need SWFObject, jQuery and Google Maps API. I thought that I could use the benefits of using:

<script type="text/javascript" src="http://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>
<script type="text/javascript">
    google.load("jquery", "1.4.1");
    google.load("swfobject", "2.2");
    google.load('maps', '2', {'callback': googleMapSetup });
</script>

But now I read somewhere (http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/) that I need to use

google.setOnLoadCallback(function() {
    // Place init code here instead of $(document).ready()
});

instead of $(document).ready().. Is this true?

Was it helpful?

Solution

There are two ways of using the Ajax Libraries API.

Firstly, you can just use Google to host your jQuery file:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Secondly you can use it to do async loads of jQuery, which is what you're referring to. If you do this the pattern is:

<script type="text/javascript" src="http://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>
<script type="text/javascript">
  google.load("jquery", "1.4.2");
  google.load("swfobject", "2.2");
  google.load('maps', '2', {'callback': googleMapSetup });
  google.setOnLoadCallback(function() {
    $(function() {
      // Place init code here instead of $(document).ready()
    });
  });
</script>

The reason you have to use google.setOnLoadCallback() is because loading jQuery in this case is asynchronous so you need to wait for jQuery to be loaded and the document to be ready.

The reason you have to use jQuery inside the load callback is because it may not be loaded anywhere else at the time you run the Javascript, leading to a potential race condition and intermittent errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top