2

I am using google ajax api How can I load custom js which depends on libs loaded by ajaxapi?

Andrey Kuznetsov
  • 11,640
  • 9
  • 47
  • 70

1 Answers1

2

You could define a function that inserts the script object into the DOM like

<script type="text/javascript">
function loadMyCustomJavaScript() {
    var script = document.createElement("script");
    script.src = "http://www.example.org/my.js";
    script.type = "text/javascript";
   document.getElementsByTagName("head")[0].appendChild(script);
}
</script>

and either use it as google.setOnLoadCallback

<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
    google.load("jquery", "1");
    google.setOnLoadCallback(loadMyCustomJavaScript);
</script>

or, if you want to load it with a specific Google library that you load, as a callback for that method, ie.

<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
  google.load("maps", "2");
  google.load("search", "1", {"callback" : loadMyCustomJavaScript});
</script>

Update: Based on your comment, you could try to use jQuery.getScript which provides a callback function for the (externally) loaded JavaScript code. According to HubLog: Google, jQuery and plugin loading, you may have to use window.setTimeout to delay the execution of a function until the script(s) has/have eval'd.

Since jQuery and it's plugins are probably loaded asynchronously, you may need to use unobtrusive JavaScript instead of using jQuery/plugin functions in the HTML code directly.

hangy
  • 10,765
  • 6
  • 43
  • 63
  • Yes I have already tryed using function like your loadMyCustomJavaScript but I need to load jquery plugins and use it but I don't know how when are they loaded. – Andrey Kuznetsov Apr 24 '10 at 20:45
  • Did my update help you? Is there anything else you need to know? – hangy Apr 27 '10 at 13:21