Javascript:在页面加载后加载外部脚本

时间:2012-05-18 11:14:33

标签: javascript sharethis

我正在使用ShareThis在我的网站上添加一个不错的社交网络共享栏。问题是它有时加载速度非常慢,并且可以暂停页面加载几秒钟。

以下内容必须包含在HTML头中:

<script type="text/javascript">var switchTo5x=true;</script>
<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript" src="http://s.sharethis.com/loader.js"></script>

然后以下是身体的底部:

<script>
var options={ "publisher": "xxxxxxxxxxxxxxxxxxxx", "position": "left", "ad": { "visible": true, "openDelay": 5, "closeDelay": 0}, "chicklets": { "items": ["facebook", "googleplus", "pinterest", "amazon_wishlist", "email", "sharethis"]}};
var st_hover_widget = new sharethis.widgets.hoverbuttons(options);
</script>

我在想,如果我可以在页面后强制加载,那么它不会减慢页面速度。是否有捷径可寻?例如,可以在加载页面后通过javascript将所有这些代码插入HTML中的正确位置,然后继续按原样加载,以便页面快速加载,然后ShareThis栏可以加载页面?

5 个答案:

答案 0 :(得分:1)

<script id="shareThisScript" type="text/javascript">var switchTo5x=true;</script>

<script type="text/javascript">
    setTimeout(function() {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = 'http://w.sharethis.com/button/buttons.js';
        var c = document.getElementById('shareThisScript');
        c.parentNode.appendChild(s, c);

        s = document.createElement('script');
        s.type = 'text/javascript';
        s.innerHTML = 'var options={ "publisher": "xxxxxxxxxxxxxxxxxxxx", "position": "left", "ad": { "visible": true, "openDelay": 5, "closeDelay": 0}, "chicklets": { "items": ["facebook", "googleplus", "pinterest", "amazon_wishlist", "email", "sharethis"]}};var st_hover_widget = new sharethis.widgets.hoverbuttons(options);';
        c.parentNode.appendChild(s, c);
    }, 10);
</script>

不确定为什么使用loader.js。它在没有它的情况下在我们的网站上运行。

答案 1 :(得分:0)

我们可以使用require.js作为脚本或模块加载器,看看它。

答案 2 :(得分:0)

听起来像是在lazy loading之后!

(function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://w.sharethis.com/button/buttons.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
})();

答案 3 :(得分:0)

你能将这份代码放在一个单独的框架中吗?然后主页面和社交栏将相互独立加载。

答案 4 :(得分:0)

使用延迟加载使用这样的按钮(但不适用于底栏):

 window.onload = function() {       
    LazyLoad.js( ['http://w.sharethis.com/button/buttons.js','http://s.sharethis.com/loader.js'], function () {
      stLight.options(
        { publisher: "xxxxxxxxxxxxxx", doNotHash: true, doNotCopy: true ,hashAddressBar: false}
      );
    }); 
  }

检查此lazyload