I'm using Google Ajax API and they suggest I use google.setOnLoadCallback()
to do various things related to their API but I'm using also jQuery's $(document).ready()
to do other JS things, not related to Google API.
Is it safe to mix these two approaches in one document? I did not notice any problems yet but I suppose it's a matter of scale.
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.
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>
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".
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);
来源:https://stackoverflow.com/questions/556406/google-setonloadcallback-with-jquery-document-ready-is-it-ok-to-mix