0

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?

8
  • 2
    This error means stLight is not there at all. Are you loading the file that contains the definition of it correctly? Commented Oct 8, 2012 at 18:54
  • Do you want it be inserted as string? Commented Oct 8, 2012 at 19:03
  • I'm loading the file that contains stLight right before I add this. Commented Oct 8, 2012 at 19:05
  • You should add this line only after that file get loaded Commented Oct 8, 2012 at 19:07
  • 1
    When loading the file, do you use onload? See: jsfiddle.net/3BMrL. Commented Oct 8, 2012 at 19:08

1 Answer 1

1

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"});
};
Sign up to request clarification or add additional context in comments.

1 Comment

This was a great suggestion. I set the first tag to a global variable because that's what it was anyway, then added the second script tag dynamically, then just executed the final statement. Worked great!! Thank you for your suggestion.

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.