소셜 미디어 버튼은 웹 사이트로드 시간을 늦 춥니 다.
저는 간단하고 빠른 웹 사이트를 만들고 있으며 가능한 한 사이트를 최적화하려고 노력하고 있습니다. 소셜 미디어 버튼이 웹 사이트 속도를 상당히 느리게하는 것을 발견했습니다. Facebook 좋아요 버튼, Twitter 버튼 및 Google+ 버튼을 포함하고 있습니다. 그래서 몇 가지 테스트를 실행했습니다.
소셜 미디어 버튼이 없는 웹 사이트 , 로딩 시간 0.24 초 :
웹 사이트 와 소셜 미디어 버튼, 로딩 시간 1.38s :
내 코드는 다음과 같습니다.
<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>
그래서 웹 사이트 로딩 시간을 늦추지 않고 이러한 소셜 버튼을로드하기 위해 몇 가지 시도를했습니다.
JavaScript를 통해 1 초 지연 후 버튼로드 :
setInterval(function(){
$("#social").html("<!-- FB --><div id="fb-root"></div>.....");
},1000);
이것은 도움이되지 않았고, 버튼이 제대로로드되지 않았고 버그가있었습니다.
문서가 준비된 후로드 버튼 :
$(document).ready(function() {
$("#social").html("<!-- FB --><div id="fb-root"></div>.....");
});
이것도 도움이되지 않았습니다. 버튼은 정상적으로로드되었지만 웹 사이트로드 시간은 여전히 1.00 초를 초과했습니다.
아이디어가 부족합니다. 웹 사이트 속도를 늦추지 않고로드하는 방법이 있습니까?
추신. 해당 테스트에서 크롬 용 페이지로드 시간 플러그인 사용
해결책:
그의 답변에 대한 CodeMonkey 덕분에 전체 페이지가로드 된 후 소셜 버튼을로드하여 결국이 문제를 해결했습니다 . HTML / 마크 업을 좀 더 깔끔하게 만들기 위해 필요한 JavaScript 코드 (소셜 미디어 버튼 용)를 별도의 파일로 옮겼습니다.
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 :
<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>
따라서이로드 타이밍이 다시 정상이 된 후 0.24 초 :
당신은 시도 할 수 있습니다
$(window).load(function() {
대신에
$(document).ready(function() {
따라서 이미지와 모든 것이로드 될 때까지 기다립니다.
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.
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
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
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.
You could try simpler oldschool alternatives like here 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
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 insights finds something to complain about with all of them 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?
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.
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 URL with the URL of you website and TEXT with a short description.
This solution requires no JavaScript and is therefore extremely lightweight. You can use logos, icon font, simple text ("Share on Facebook").
I also wrote a blog post that covers many other social networks.
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 here for information about how you can load the JS SDK in a non-blocking way using iframes.
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:
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:
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.
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
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.
Inside the scripts that load the social media, put "defer" in them.
<script defer src="http://api.facebook.com/....."></script>
Try to use async loading for Social init scripts:
<script async="async">...</script>
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.
Try putting your like button into reusable iframe and pass the url to like.
<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>
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:
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.
또 다른 해결책은 소셜 플러그인을 iframe에로드하는 sdk로 래핑하는 것입니다. FB API는 부모 창의 window.onload를 기다리지 않고 소셜 플러그인을 더 일찍 렌더링합니다.
참고 URL : https://stackoverflow.com/questions/19060289/social-media-buttons-slow-down-website-load-time
'program story' 카테고리의 다른 글
Java 내에서 Python 사용 (0) | 2020.12.13 |
---|---|
이미 다른 포크를 포크 한 경우 원래 리포지토리를 포크하려면 어떻게해야합니까? (0) | 2020.12.13 |
템플릿 매개 변수에 의존하는 인수가 없습니다. (0) | 2020.12.12 |
app.config에서 ClientSettingsProvider.ServiceUri의 용도 (0) | 2020.12.12 |
클래스 및 인스턴스 메서드의 차이점 (0) | 2020.12.12 |