Google and jQuery (and others)

I’ve spent the last 30 minutes Googling for help to use Google’s AJAX Libraries API. You know what? The solution was right there on that page.

My problem was that I could get a jQuery example to work if I loaded the API like this

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" >
	// Do whatever
</script>

but I couldn’t get the example to work if I used the recommended

<script src="http://www.google.com/jsapi"></script>
<script>
	google.load("jquery", "1.2.6");
	// Do whatever
</script>

Are you in the same boat? Short and simple, here’s the solution:

<script src="http://www.google.com/jsapi"></script>
<script>
	google.load("jquery", "1.2.6");

	google.setOnLoadCallback(function() {
		// Do whatever
	});
</script>

Yep, you’ve got to put all your jQuery code inside the google.setOnLoadCallback method. Use the following to test that it works for you.

<html>
	<head>
		<script src="http://www.google.com/jsapi"></script>
		<script>
			google.load("jquery", "1.2.6");

			google.setOnLoadCallback(function() {
				$("a").click(function(event){
					event.preventDefault();
					$(this).hide("slow");
				});
			});
		</script>
	</head>
	<body>
		<a href="http://jquery.com/">jQuery</a>
	</body>
</html>

Leave a Reply

 

Staypressed theme by Themocracy