is it possible to unite several async social butto

2019-04-17 10:59发布

So far I've these 3 social buttons at the end of the page. I was thinking that rewriting same function 3 times isn't very smart. Could I unite them? would it work?

Any ideas how to do this? logically I would do: g.src = 'http://apis.google.com/js/plusone.js', 'http://connect.facebook.net/en_US/all.js#xfbml=1', 'http://platform.twitter.com/widgets.js';

but I'm not sure if this correct way to do it...

<script type="text/javascript">
//<![CDATA[
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.async = true;
g.src = 'http://apis.google.com/js/plusone.js';
s.parentNode.insertBefore(g, s);
})(document, 'script');
//]]>
</script>


<script type="text/javascript">
//<![CDATA[
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.async = true;
g.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1';
s.parentNode.insertBefore(g, s);
})(document, 'script');
//]]>
</script>


<script type="text/javascript">
//<![CDATA[
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.async = true;
g.src = 'http://platform.twitter.com/widgets.js';
s.parentNode.insertBefore(g, s);
})(document, 'script');
//]]>
</script>

2条回答
Evening l夕情丶
2楼-- · 2019-04-17 11:50
var scripts = ["http://apis.google.com/js/plusone.js","http://connect.facebook.net/en_US/all.js#xfbml=1","http://platform.twitter.com/widgets.js"];
(function(array) {
   for (var i = 0, len = array.length; i < len; i++)
   {
      var elem = document.createElement('script');
      elem.type = 'text/javascript';
      elem.async = true;
      elem.src = array[i];
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(elem, s);
   }
})(scripts);

This is my solution, tested on Chrome and Mozilla under Linux!

查看更多
闹够了就滚
3楼-- · 2019-04-17 11:53

Try:

<script type="text/javascript">
//<![CDATA[
(function(d, t) {
var gplus = d.createElement(t), fb = d.createElement(t), twt = d.createElement(t),

// google plus
gplus.async = true,
gplus.src = 'http://apis.google.com/js/plusone.js',

// facebook
fb.async = true,
fb.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1',

// twitter
twt.async = true,
twt.src = 'http://platform.twitter.com/widgets.js',    

s = d.getElementsByTagName(t)[0];

s.parentNode.insertBefore(gplus, s);
s.parentNode.insertBefore(fb, s);
s.parentNode.insertBefore(twt, s);
})(document, 'script');
//]]>
</script>
查看更多
登录 后发表回答