2012-02-05 48 views
2

我試圖將Reddit按鈕添加到我的網站,但它們不是異步的,並且Reddit往往滯後,減慢了頁面加載速度。當我看到劇本返回什麼,我得到的是這樣的:使reddit的按鈕異步

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

我嘗試了頁面加載後,將其注入到我的網頁。我頁面加載後,試圖在JavaScript這兩種方法都無濟於事:

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); 

其中placeholder是一個DOM元素<div class="reddit-button"></div>。關於如何去做這件事的任何想法?

回答

1

可以「覆蓋」的document.write方法:

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); 
}; 

通過這種方式,外部代碼可以調用document.write,因爲它要和你推到HTML的適當位置文檔中爲多。

Live test case - 在Chrome,Firefox和IE9下測試OK,所以猜測它應該足夠了。