2

I'm trying to add Reddit buttons to my site, but they are not asynchronous, and Reddit tends to lag, slowing down page loads. When I look at what the script returns, I get something like this:

(function () {
    var write_string = ...
    document.write(write_string);
})()

I try to inject it into my page after a page load. I've tried both these methods in javascript after page load to no avail:

placeholder.innerHTML = '<script type="text/javascript" src="http://www.reddit.com/buttonlite.js?i=5"></script>'

var js = document.createElement('script');
js.type = 'text/javascript';
js.src = 'http://www.reddit.com/buttonlite.js?i=5';
placeholder.appendChild(js);

where placeholder is a DOM element <div class="reddit-button"></div>. Any ideas on how I could go about this?

1 Answer 1

1

You can "override" the document.write method:

window.onload = function() {
    var oScript = document.createElement("script");
    document.write = function(text) {
        document.getElementById("placeholder").innerHTML += text;
    };
    oScript.src = "http://www.reddit.com/buttonlite.js?i=0";
    document.body.appendChild(oScript);
};

This way the external code can call document.write as much as it wants to and you push the HTML to the proper place in your document.

Live test case - Tested OK under Chrome, Firefox and IE9 so guess it should be enough.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.