使用jQuery $(document).ready()的google.setOnLoadCallback,可以混合使用吗?

zgo*_*oda 56 javascript jquery onload google-ajax-api

我正在使用Google Ajax API,他们建议我使用google.setOnLoadCallback()与他们的API相关的各种事情,但我也使用jQuery $(document).ready()来做其他JS事情,与Google API无关.

将这两种方法混合在一个文档中是否安全?我没有注意到任何问题,但我认为这是一个规模问题.

cle*_*tus 68

你几乎必须这样做:

google.setOnLoadCallback(function() {
  $(function() {
    // init my stuff
  });
});
Run Code Online (Sandbox Code Playgroud)

你不能$(document).ready()没有$(jQuery对象)可用,所以需要进入回调.而且您无法确定文档在回调中是否已准备就绪,因此您必须这样做ready().


小智 49

很抱歉从死里复活,但1)它仍然是这个问题的"答案",2)我找到了一个更好的解决方案.

在函数上有一个可选的第3个参数,google.load它接受配置选项的对象.其中一个选择是callback.它也摆脱了单独setOnLoadCallback呼叫的需要.

例如

google.load('visualization', '1.0', {
    'packages': "charttype", 
    'callback': $jQ.proxy(me.setupChart, me)
});
Run Code Online (Sandbox Code Playgroud)

所以:

<script src="https://www.google.com/jsapi"></script>
<script>
$(document).ready(function () {
    function mapsLoaded() {
        etc etc etc
    }

    google.load("maps", "2", {"callback" : mapsLoaded});
});
</script>
Run Code Online (Sandbox Code Playgroud)

请参阅:https: //developers.google.com/loader/#Dynamic


and*_*ndy 6

如果您的JavaScript代码驻留在自己的js文件中而不是HTML文档中,您也可以在文档中执行此操作:

<script>
        google.load("jquery", "1.7.0");
        google.load("jqueryui", "1.8.16");
        google.setOnLoadCallback(function() {
             var script = document.createElement("script");
             script.setAttribute("type", "text/javascript");
             script.setAttribute("src", "my.js");
             document.getElementsByTagName("html")[0].appendChild(script);
        });
</script>
Run Code Online (Sandbox Code Playgroud)

my.js是从谷歌加载所有其他东西后加载.在您的my.js文件中,您可以这样做$(document).ready(...).因此,您的应用程序代码独立于"由Google加载"或"直接从您的服务器加载".