Google.load custom js

I am using google ajax api How can I load custom js that depend on the libs loaded by ajaxapi?

+2


a source to share


1 answer


You can define a function that inserts a 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 like 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 using a specific google library you are loading as a callback for that method, that is

<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 can try using jQuery.getScript , which provides a callback for the loaded (externally) JavaScript code. According to HubLog: Google download, jQuery and plugins , you may need to use window.setTimeout

to delay the execution of a function until script (s) has / has eval'd.

Since jQuery and its plugins are likely to load asynchronously, you may want to use unobtrusive JavaScript instead of using jQuery / plugin functions directly in your HTML code.

+2


a source







All Articles