1

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

1 回答 1

7

根据您的解释,您的页面似乎设置如下:

<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>

但是,这不会像您期望的那样工作,因为document.ready在 DOM 完全加载之前事件不会触发。然而,JavaScript 文件在加载时执行。所以实际的执行是这样的:

  1. 加载谷歌 JSAPI
  2. 加载 jQuery
  3. 加载 External.js
  4. 呼叫文件准备就绪

根据其余代码的外观,您可能希望将所有初始化代码放在单独的文件中,或者将search负载移回主文档。

关于不引人注目的代码:

大卫,不显眼的 JavaScript 与它如何影响页面有关,而不是它是在页面内还是在外部。

更重要的是不要让您的网站如此依赖 JavaScript,以致在禁用它的情况下它无法运行

例如,这是突兀的:

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

因为它只能在启用 JavaScript 的情况下工作。此外,代码是内联的,这很糟糕,因为它没有将功能与结构 (HTML) 分开。

但是,采用类似的代码:

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

并使用这个 javascript/jquery 片段:

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

Is 变得不显眼,因为页面仍然有效(默认加载 /do/something),但是当 JavaScript 启用时它以更好的方式工作(执行 javascript 而不是加载该 url)。这也称为渐进增强。

于 2009-12-27T21:43:05.990 回答