WEBOPIXEL

ローカル環境でFacebook&Twitterウィジェットを開いたときに重いのをなんとかする

Posted: 2013.01.21 / Category: javascript / Tag: ,

FacebookやTwitterのウィジェットやボタンを埋め込んだhtmlファイルをローカルで直接開くと表示されなくて、さらにWindows環境だと読み込みにすごく時間が掛かってしまいます。(Macだとあまり気にならないですが)
そこでjQueryを使用してサーバー環境時のみウィジェットを表示する方法をご紹介します。

Sponsored Link

Facebook iframeバージョン

普通にFacebookのウィジェットをiframeで埋め込んだ例です。
適当なidでマークアップしておきます。ここでは「facebook」としました。

html

	<div id="facebook">
		<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&amp;width=292&amp;height=590&amp;show_faces=true&amp;colorscheme=light&amp;stream=true&amp;border_color&amp;header=true" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:590px;" allowTransparency="true"></iframe>
	</div>
	

このままでは重いのでiframeのことろは削除しておきます。

html

	<div id="facebook">
	</div>
	

削除したiframeの部分をjQueryで再配置します。

jQuery

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
	<script type="text/javascript">
	$(function(){
		if (location.protocol !== 'file:') {
			$('#facebook').replaceWith('<div id="facebook"><iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fyokohamainsatsu&amp;width=290&amp;height=200&amp;show_faces=false&amp;colorscheme=light&amp;stream=true&amp;border_color&amp;header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:290px; height:200px;" allowTransparency="true"></iframe></div>');
		}
	});
	</script>
	

ローカルで直接htmlファイルを開いたときはprotocolが「file:」となりますので、それ以外だったらappendとすればローカルでは読み込みません。

Twitter JSバージョン

TwitterのウィジェットはJSで入れますね。(FacebookもJSバージョンがありますが)

html

	<a class="twitter-timeline" href="https://twitter.com/xxxxxxxx" data-widget-id="xxxxxxxxxxxxxxxxxxx" lang="JA">@xxxxxxxxxxxからのツイート</a>
	<script>
	!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
	</script>
	

このJSをさきほどの「location.protocol」のif文で囲むだけです。

html

	<a class="twitter-timeline" href="https://twitter.com/xxxxxxxx" data-widget-id="xxxxxxxxxxxxxxxxxxx" lang="JA">@xxxxxxxxxxxからのツイート</a>
	<script>
	if (location.protocol !== 'file:') {
	!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
	}
	</script>