我有一个页面需要 SWFObject、jQuery 和 Google Maps API。 我认为我可以利用以下好处:
<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>
但现在我在某处读到( http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/ ) 我需要使用
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
});
而不是 $(document).ready().. 这是真的吗?
最佳答案
有两种使用 Ajax 库 API 的方法。
首先,您可以使用 Google 来托管您的 jQuery 文件:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
其次,您可以使用它来异步加载 jQuery,这就是您所指的。如果你这样做,模式是:
<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>
您必须使用 google.setOnLoadCallback()
的原因是因为在这种情况下加载 jQuery 是异步的,因此您需要等待 jQuery 加载和文档做好准备。
您必须在加载回调中使用 jQuery 的原因是因为在您运行 Javascript 时它可能不会在其他任何地方加载,从而导致潜在的竞争条件和间歇性错误。
关于jquery - 适用于 jQuery 的 Google AJAX 库 CDN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367977/