Pergunta

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

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top