1

I am loading a script from the google plus button only when the user requests it. The code that is used is the following:

    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);

When I fire this script it will change the placeholder into the google plus button. The placeholder looks like this:

<g:plusone size="tall" annotation="none"></g:plusone>

There are a few other buttons I load like this, only when needed.

Now sometimes the buttons take a while to load. Is there a way get an alert when all the buttons are loaded.

I can then just display a loader until it is fully loaded, and then display it nicely.

I use jQuery as my javascript framework.

Edit

For a better solution check out this question: Invoking handler when all scripts finished loading via $.getScript

A better way to go is using jQueries deffered object. I added a small example and fiddle to the answer.

2 Answers 2

2

jQuery provides a mechanism to define a script load handler:

$.getScript( 'https://apis.google.com/js/plusone.js', function () {
    // the script has loaded and executed
});

This handler is invoked after the script has executed, so it should suit your needs...

Sign up to request clarification or add additional context in comments.

3 Comments

Ah yes this was the function I was searching for. Do you know if this works also for multiple files. Only fire the function when all the scripts are done loading.
@Saif: It might return a deferred object which you can then use together with $.when.
@SaifBechan I've opened this question to address the issue...
1

If you want to add the feature without modifying existing content, use the code below:

(function(){
    var poller = window.setInterval(function(){//Set poller
        if($('g\\:plusone').length == 0){      // When the document doesn't have
            clearInterval(poller);             // any g:plusone elements, clear
                                               // poller, and execute your code
            //Run your code..
        }
    }, 200);  //Checks at a frequence of 200ms
})();

1 Comment

Interesting approach. I guess this will work for multiple elements also. I can just add a unique class to all the elements, and when they are all filles I can clear the poller. I will check this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.