Html 社交媒体按钮会减慢网站加载时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19060289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Social media buttons slow down website load time
提问by
I'm creating a simple and fast website, and I'm trying to optimize the site as much as I can. I noticed that social media buttons are slowing down the website by quite a lot. I'm including the Facebook Like Button, Twitter Button and Google+ Button. So I ran a few tests:
我正在创建一个简单而快速的网站,并且正在尽可能地优化该网站。我注意到社交媒体按钮大大降低了网站速度。我包括 Facebook Like Button、Twitter Button 和 Google+ Button。所以我进行了一些测试:
Website withoutsocial media buttons, loading time 0.24s:
没有社交媒体按钮的网站,加载时间 0.24s:
Website withsocial media buttons, loading time 1.38s:
带有社交媒体按钮的网站,加载时间 1.38 秒:
Here is my code:
这是我的代码:
<div id="social">
<!-- FB -->
<div id="fb-root"></div>
<script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_EN/all.js#xfbml=1&status=0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://facebook.com/textsearcher" data-width="150" data-layout="button_count" data-show-faces="false" data-send="false"></div>
<!-- TWITTER -->
<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.textsearcher.com/" data-hashtags="TextSearcher">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<!-- G+ -->
<div class="g-plusone" data-size="medium" data-href="http://www.textsearcher.com/"></div>
<script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script>
</div>
So I tried few things to load these social buttons without them slowing website load time.
所以我尝试了一些方法来加载这些社交按钮,而不会减慢网站加载时间。
Loading buttons after one second delay via JavaScript:
通过 JavaScript 延迟一秒后加载按钮:
setInterval(function(){
$("#social").html("<!-- FB --><div id="fb-root"></div>.....");
},1000);
This did not help, buttons didn't load up properly and they were bugging.
这没有帮助,按钮没有正确加载并且它们在窃听。
Loading buttons after document is ready:
文档准备好后加载按钮:
$(document).ready(function() {
$("#social").html("<!-- FB --><div id="fb-root"></div>.....");
});
This did not help either. Buttons loaded just fine but website load time was still >1.00 seconds.
这也没有帮助。按钮加载得很好,但网站加载时间仍然 > 1.00 秒。
I'm running out of ideas. Any way to load them without slowing down website?
我的想法不多了。有什么方法可以在不减慢网站速度的情况下加载它们?
PS. Used Page load timeplugin for chrome in those tests
附注。使用页面加载时间在这些测试插件铬
SOLUTION:
解决方案:
Thanks to CodeMonkey for his answer, I eventually solved this problem by loading social buttons after entirepage is loaded. I moved the necessary JavaScript code (for social media buttons) in a separate file to make my HTML/markup little bit cleaner.
感谢 CodeMonkey 的回答,我最终通过在整个页面加载后加载社交按钮来解决这个问题。我将必要的 JavaScript 代码(用于社交媒体按钮)移动到一个单独的文件中,以使我的 HTML/标记更简洁一些。
JS (in a seperate file, social.js):
JS(在一个单独的文件,social.js):
/* Facebook*/
(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_EN/all.js#xfbml=1&status=0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));
/* Twitter */
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
/* G+ */
(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();
HTML:
HTML:
<script>
$(window).bind("load", function() {
$.getScript('js/social.js', function() {});
});
</script>
<!-- FB -->
<div id="fb-root"></div>
<div class="fb-like" data-href="http://facebook.com/textsearcher" data-width="150" data-layout="button_count" data-show-faces="false" data-send="false"></div>
<!-- TWITTER -->
<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.textsearcher.com/" data-hashtags="TextSearcher">Tweet</a>
<!-- G+ -->
<div class="g-plusone" data-size="medium" data-href="http://www.textsearcher.com/"></div>
So after this load timings were normal again, 0.24s:
所以在这个加载时间再次正常之后,0.24s:
采纳答案by CodeMonkey
You could try
你可以试试
$(window).load(function() {
instead of
代替
$(document).ready(function() {
so it will wait until after your images and everything has loaded.
所以它会等到你的图像和一切都加载后。
If that doesn't help, then I would suggest having them only appear on hover. Have a bunch of static images / CSS sprites, that get replaced when the user hovers over them.
如果这没有帮助,那么我建议让它们只出现在悬停时。有一堆静态图像/CSS 精灵,当用户将鼠标悬停在它们上面时会被替换。
If you don't want that extra step, and you have server access to install modules you can try google's mod pagespeed to defer the javascript for you https://developers.google.com/speed/pagespeed/module/filter-js-defer
如果您不想要额外的步骤,并且您有服务器访问权限来安装模块,您可以尝试使用 google 的 mod pagespeed 为您推迟 javascript https://developers.google.com/speed/pagespeed/module/filter-js-推迟
If you don't have server access you can try the CDN route, Cloudflare's rocket loader is very interesting, I am testing it at the minute for similar reasons, and see ~ 33% speed increase http://www.cloudflare.com/features-optimizer
如果没有服务器可以试试CDN路线,Cloudflare的火箭加载器很有意思,我也是为了类似的原因,一分钟测试一下,看速度提升了~33% http://www.cloudflare.com/功能优化器
If that doesn't help you could try the old favourite of sticking the buttons at the bottom of the page and repositioning with CSS so they look higher up; that way you can have them where you want them but they don't seem to interfere with the page load time.
如果这没有帮助,您可以尝试将按钮粘贴在页面底部并使用 CSS 重新定位,以便它们看起来更高;这样你就可以把它们放在你想要的地方,但它们似乎不会干扰页面加载时间。
You could try simpler oldschool alternatives like here http://zurb.com/article/883/small-painful-buttons-why-social-media-bu
你可以尝试像这里这样的更简单的老式替代品http://zurb.com/article/883/small-painful-buttons-why-social-media-bu
or see if service like http://www.addthis.com/or http://www.sharethis.com/work any faster for you
或者看看像http://www.addthis.com/或http://www.sharethis.com/这样的服务是否对你来说更快
Of course the elephant in the room at this point is that to have the 3 main social media buttons on the page, and for it to only cost you a second - sadly seems quite good! They are deceptively complicated buttons that don't seem well optimised, google pagespeed insightsfinds something to complain about with all of them iirc.
当然,此时房间里的大象是在页面上有 3 个主要的社交媒体按钮,而且它只花你一秒钟 - 可悲的是看起来相当不错!它们是看似复杂的按钮,似乎没有得到很好的优化,谷歌页面速度见解发现所有这些都可以抱怨 iirc。
Since you are taking a 100%+ speed hit, I would suggest some A/B testing to see if you really need them, i.e. for your site does being slower decrease traffic? Does having the share buttons bring in more traffic to warrant their presence?
由于您的速度达到了 100% 以上,我建议您进行一些 A/B 测试,看看您是否真的需要它们,即对于您的网站来说,速度变慢会减少流量吗?共享按钮是否会带来更多流量以保证它们的存在?
回答by Stefan
While this question is old and the person asking probably won't see my response, here is an alternative for anyone with the same issue -- as long as you don't mind sacrificing showing the number of likes/shares/etc.
虽然这个问题很老,问的人可能不会看到我的回答,但对于有同样问题的人来说,这里有一个替代方案——只要你不介意牺牲点赞/分享/等的数量。
You can simply add links that send the visitor to the actual social network and open a sharing window with pre-filled URL and description.
您可以简单地添加将访问者发送到实际社交网络的链接,并打开一个带有预填充 URL 和描述的共享窗口。
The code is very simple and you can use any image or text you want, which will make it easier to fit the buttons in with your site's design.
代码非常简单,您可以使用任何您想要的图像或文本,这将使按钮更容易适应您网站的设计。
<a href="https://www.facebook.com/sharer/sharer.php?u=URL" target="_blank">Share on Facebook</a>
<a href="https://twitter.com/intent/tweet?url=URL&text=TEXT&via=YOURTWITTERACCOUNTNAME" target="_blank">Tweet</a>
<a href="https://plus.google.com/share?url=URL" target="_blank">Share on Google+</a>
Simply replace URLwith the URL of you website and TEXTwith a short description.
只需将URL替换为您网站的 URL,并将TEXT替换为简短的描述。
This solution requires no JavaScript and is therefore extremely lightweight. You can use logos, icon font, simple text ("Share on Facebook").
此解决方案不需要 JavaScript,因此非常轻量级。您可以使用徽标、图标字体、简单文本(“在 Facebook 上分享”)。
I also wrote a blog post that covers many other social networks.
我还写了一篇涵盖许多其他社交网络的博客文章。
回答by AndrewF
The social widgets should not be slowing down your load time too much, unless they are blocking more important scripts that are waiting for the page to finish loading. The code you're using is asynchronous, which helps, but in most browsers this will still block the window.onload
event. See Stoyan's post herefor information about how you can load the JS SDK in a non-blocking way using iframes.
社交小部件不应过多地减慢您的加载时间,除非它们阻止了等待页面完成加载的更重要的脚本。您使用的代码是异步的,这有帮助,但在大多数浏览器中,这仍会阻止window.onload
事件。有关如何使用 iframe 以非阻塞方式加载 JS SDK 的信息,请参阅Stoyan 的帖子。
If that's too much, and you want to delay the SDK downloading or running (and speed it up once it does run), here is my recommendation:
如果这太多了,并且您想延迟 SDK 下载或运行(并在运行后加快速度),我的建议是:
First, either use a library like jQuery that provides a way to hook into the DOM being ready in a cross-platform fashion. Here is one implementation. Once you have your "DOM ready handler", you should do one of the following two things:
首先,要么使用像 jQuery 这样的库,它提供了一种以跨平台方式连接到准备好的 DOM 的方法。这是一个实现。一旦你有了“DOM 就绪处理程序”,你应该做以下两件事之一:
Move the JS SDK loading code into your DOM ready handler.
Take xfbml: true out of FB.init(...), if you have it (in this case, you don't), and take xfbml=1 out of the SDK URL. This prevents social widgets from being parsed and initialized immediately. Then, call FB.XFBML.parse() in your DOM ready handler. See the documentation here for that method. The best thing to do for performance would be to specifically call
FB.XFBML.parse(document.getElementById(''))
so that the SDK doesn't waste time going over the whole DOM.
将 JS SDK 加载代码移动到您的 DOM 就绪处理程序中。
从 FB.init(...) 中取出 xfbml: true,如果您有它(在本例中,您没有),并从 SDK URL 中取出 xfbml=1。这可以防止社交小部件被立即解析和初始化。然后,在 DOM 就绪处理程序中调用 FB.XFBML.parse()。请参阅此处的文档了解该方法。为了提高性能,最好的办法是专门调用,
FB.XFBML.parse(document.getElementById(''))
这样 SDK 就不会浪费时间遍历整个 DOM。
回答by Luke111
The plugin (social media button) load times will vary depending on a number of factors, including (but not limited to):
插件(社交媒体按钮)加载时间取决于多种因素,包括(但不限于):
- Your server's response time (Plugins don't load until your code tells them too.)
- The user's internet speed (in this case, yours)
- The distance to the social media website's server (for instance, Facebook's server could be located on the other side of the continent, creating latency)
- The load time of the social media website altogether
- 您的服务器的响应时间(直到您的代码也告诉它们插件才会加载。)
- 用户的互联网速度(在这种情况下,您的)
- 与社交媒体网站服务器的距离(例如,Facebook 的服务器可能位于大陆的另一端,从而造成延迟)
- 整个社交媒体网站的加载时间
This means that there is not much you can do besides make your code as optimized as possible.
这意味着除了尽可能优化您的代码之外,您无能为力。
Also, it is good practice to run your Javascript plugins after the document is ready, unless otherwise specified by the plugin documentation. The setInterval is not a good approach, as it doesn't know if all the page is ready to be modified or not. So please make sure to use the $(document).ready()
approach for doing anything that modifies the page content.
此外,除非插件文档另有规定,否则最好在文档准备好后运行 Javascript 插件。setInterval 不是一个好方法,因为它不知道所有页面是否都准备好进行修改。所以请确保使用这种$(document).ready()
方法来做任何修改页面内容的事情。
回答by Kernel James
Inside the scripts that load the social media, put "defer" in them.
在加载社交媒体的脚本中,将“延迟”放入其中。
<script defer src="http://api.facebook.com/....."></script>
回答by paka
Try to use async loading for Social init scripts:
尝试对 Social init 脚本使用异步加载:
<script async="async">...</script>
回答by boateng
Try putting your like button into reusable iframe and pass the url to like.
尝试将您的喜欢按钮放入可重复使用的 iframe 并将 URL 传递给喜欢。
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fphys.org" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px;" allowTransparency="true"></iframe>
回答by lukyer
If you came here to find solution how to load facebook social plugins faster - e.g. how to render them BEFORE window.onload() event occures (because of slow network on wifi / large image on page / ...) you may try my solution:
如果你来这里是为了寻找如何更快地加载 Facebook 社交插件的解决方案——例如如何在 window.onload() 事件发生之前渲染它们(因为 wifi 上的网络缓慢/页面上的大图像/...)你可以试试我的解决方案:
window.fbAsyncInit = function () {
dispatchEvent(new Event('load'));
}
fbAsyncInit is called as soon as facebook sdk js file is loaded (e.g. fast) and you can fake social buttons to render earlier (before other resources like images are loaded) using custom load event dispatching. Be aware of consequences when you fire onload() event earlier depending on your other javascript code/libraries.
fbAsyncInit 在 facebook sdk js 文件加载(例如快速)后立即调用,您可以使用自定义加载事件调度来伪造社交按钮以更早地呈现(在加载其他资源如图像之前)。请注意根据其他 javascript 代码/库提前触发 onload() 事件时的后果。
Another solution is to wrap your social plugin with sdk loading into iframe. FB API will not wait for window.onload of parent window and will render social plugins earlier.
另一种解决方案是将您的社交插件与 sdk 加载到 iframe 中。FB API 不会等待父窗口的 window.onload 并且会更早地呈现社交插件。
回答by Muskie
Most of the major social media buttons offer an asynchronous version of their JavaScript. You just have to scroll a little further down on the official documentation pages.
大多数主要的社交媒体按钮都提供其 JavaScript 的异步版本。您只需在官方文档页面上向下滚动一点。