到目前为止,我在页面末尾有这3个社交按钮。我以为重写相同的功能3次并不是很聪明。我可以团结他们吗?会有用吗?
任何想法如何做到这一点?逻辑上我会这样做: 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';
但我不确定这种方法是否正确......
<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>
答案 0 :(得分:5)
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);
这是我的解决方案,在Linux下在Chrome和Mozilla上测试过!
答案 1 :(得分:1)
尝试:
<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>