google.setOnLoadCallback with jQuery $(document).ready(), is it OK to mix?

亡梦爱人 提交于 2019-11-27 06:35:50
cletus

You pretty much have to do this:

google.setOnLoadCallback(function() {
  $(function() {
    // init my stuff
  });
});

You can't do $(document).ready() without $ (the jQuery object) being available, so that needs to go inside the callback. And you can't be sure the document is ready inside the callback, so you have to do ready() too.

Dawn

Sorry to be raising this from the dead, but 1) It still comes up as an 'answer' to this problem and 2) I've found a better solution.

There is an optional 3rd argument on the google.load function that takes an object of configuration options. One of the options is callback. It also gets rid of the need for a separate setOnLoadCallback call.

E.g.

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

So:

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

    google.load("maps", "2", {"callback" : mapsLoaded});
});
</script>

See: https://developers.google.com/loader/#Dynamic

If your JavaScript code resides in its own js file and not inside the HTML document you could also do this in the document:

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

This loads my.js after all other stuff is loaded from google. In your my.js file you can then do $(document).ready(...). So your application code is independent from "loaded by google" or "loaded directly from your server".

Vincent

Why mix when you can do it all with $(document).ready()? Just get rid of the google.setOnLoadCallback function and use jQuery's $(document).ready().

This:

google.setOnLoadCallback(chartEnrollment);

becomes

$(document).ready(chartEnrollment);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!