views:

233

answers:

1

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"&gt;&lt;/script&gt;
<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?

+2  A: 

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"&gt;&lt;/script&gt;

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"&gt;&lt;/script&gt;
<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.

cletus
yes, but i can't use $(document).ready() anymore than in your second option?
FFish
@FFish: if you do `$(function() { ... }` outside the load callback jQuery might not be loaded yet, leading to JS errors.
cletus
can you tell me, what is $(function(){}) exactly?I always just put all my code in doc.ready, all functions and everything, because I am a monkey.
FFish
@FFish: `$(function() { ... });` is equivalent to `$(document.ready(function() { ... });`. It means run that code when the document is "ready", meaning the markup is loaded but images aren't necessarily loaded yet. See http://api.jquery.com/ready/
cletus
One more question.. how can I use google.setOnLoadCallback to load my external .js file with the jQuery code?
FFish
@FFish: hopefully your external JS file only contains functions (ie no code is executed when the file is simply loaded). If so, just do it immediately. If not, I would move the auto-loaded code to a function and call it in the load callback.
cletus