0

Possible Duplicate:
how to check the script element load event accross browser without jquery

I'm writing a page to generate graphs for someone. I'm using the Google Charts API.

I want to load the API dynamically. I'm having problems with the 'google' global object. How can I detect whether it has been declared? If it were my own script I think I could use call back. Currently i have :

var addScript = function(src){
    var head= document.getElementsByTagName('head')[0];
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.src= src;
    head.appendChild(script);
}

var init = function (){           

    addScript('https://www.google.com/jsapi');

    var waitForScript = setInterval(function(){

        if(window['google']!==undefined){
            window.clearInterval(waitForScript);
            google.load('visualization', '1.0', {
                'packages':['corechart']
            });


        }

    },50);

}

Any help would be much appreciated!

Community
  • 1
  • 1
  • Use the `load` event of the dynamically created ` – Bergi Dec 11 '12 at 11:15
  • possible duplicate of [how to check the script element load event accross browser without jquery](http://stackoverflow.com/questions/12574549/how-to-check-the-script-element-load-event-accross-browser-without-jquery) or [dynamic script loading synchronization](http://stackoverflow.com/questions/774752/dynamic-script-loading-synchronization) – Bergi Dec 11 '12 at 11:21

1 Answers1

1

The existence of a property will always autocast to true, so it will suffice to do:

if (window['google']) {
//do stuff
};

Also, in Opera you are not guaranteed to always have a head tag. So you do script appends like this:

var addScript = function(src){
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.src= src;
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
}
flavian
  • 28,161
  • 11
  • 65
  • 105