views:

208

answers:

1
+1  Q: 

google.load issue

Hi I am messing around with google ajax api at the momemt and following the examples from the documentation I have two script tags in my html file:

<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">google.load('search', '1');</script>

All works fine, but it will not work when I am using jquery and trying to call the google.load('search', '1'); in an external javascript file after $(document).ready(function()

I get the following error: null is null or not an object.

I am obviously missing something fundamental as I am just learning javascript but I was under the impression that it is best to use javascript unobtrusively. The second script tag that actually contains some js code isnt unobtrusive. Can anyone lend any help with this please?

+4  A: 

From what you have explained it seems your page is setup something like this:

<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
    google.load('jquery');
    $(document).ready(function(){
       ... do stuff ...
    });
</script>
<script src="/my/external.js" type="text/javascript"></script>

However, this will not work as you expect since the document.ready event will not fire until the DOM is completely loaded. JavaScript files, however, are executed as they are loaded. So the actual execution looks like this:

  1. Load Google JSAPI
  2. Load jQuery
  3. Load External.js
  4. Call Document Ready

Depending on what the rest of your code looks like, you might want to either put all your initialization code in a separate file, or move your search load back into the main document.

ABOUT UNOBTRUSIVE CODE:

David, unobtrusive JavaScript has to do with how it affects the page, not with whether or not it is in-page or external.

It is more about not making your site so dependent on JavaScript that it does not function with it disabled

For instance, this is obtrusive:

<a href="#" onclick="doSomething(); return false;">Click Me</a>

Because it will only work with JavaScript enabled. Additionally the code is inline which is bad because it does not separate functionality from structure (HTML).

However, taking a similar piece of code:

<a href="/do/something" id="do-something">Click Me</a>

and using this javascript/jquery snippet:

$(document).ready(function(){
    $("#do-something").click(function(e){
       doSomethingNicer();
       e.preventDefault(); // Keep the browser from following the href
    });
});

Is becomes unobtrusive because the page still works (loads /do/something by default), but it works in a nicer way when JavaScript is enabled (executes the javascript instead of loading that url). This is also called Progressive Enhancement.

Doug Neiner