user699242
user699242

Reputation: 1833

Dynamically insert a script tag without calling function

I'm trying to dynamically insert the following:

var downloadJsOnLoad = function () {

    var shareThisOne = document.createElement('script');
    shareThisOne.text = 'var switchTo5x=true;';
    document.body.appendChild(shareThisOne);

    var shareThisTwo = document.createElement('script');
    shareThisTwo.src = 'http://w.sharethis.com/button/buttons.js';
    document.body.appendChild(shareThisTwo);

    var text = 'stLight.options({publisher: "a8cae9ce-ebee-4346-9891-a1bfb0aa7005"});';

    var shareThisThree = document.createElement('script');
    shareThisThree.innerHTML = text;
    document.body.appendChild(shareThisThree);

}

jQuery(window).load(function () {
    downloadJsOnLoad();
});

Everything works, but I get an error when this javascript is parsed that says stLight is undefined. I'm assuming that it is looking at the stLight.options method as an executable rather than a plain string. How can I get around this to avoid the error?

Upvotes: 0

Views: 682

Answers (1)

pimvdb
pimvdb

Reputation: 154838

Use onload to make sure the ShareThis code (i.e. the stLight variable) exists when using it:

shareThisTwo.onload = function() {
    var text = 'stLight.options({publisher: "a8cae9ce-ebee-4346-9891-a1bfb0aa7005"});';

    var shareThisThree = document.createElement('script');
    shareThisThree.innerHTML = text;
    document.body.appendChild(shareThisThree);
};

That said, why not just discard the last element creation? You just want to execute code.

shareThisTwo.onload = function() {
    stLight.options({publisher: "a8cae9ce-ebee-4346-9891-a1bfb0aa7005"});
};

Upvotes: 1

Related Questions