分享

JS延迟加载百度分享代码,提高网页速度

 怡窝馆 2014-07-25

JS延迟加载百度分享代码,提高网页速度

相信大家经常在一些网站上看到有快捷分享到各大流行网站的按钮,目前流行的有JiaThis、百度分享、Bshare等,目前用百度分享的居多。

发现很多网站在放置百度分享代码的时候,简单的将分享代码放置到固定的网页位置就完事了,这是非常致命的方式。因为,我经常打开一个网页的时候,发现在网页加载到分享代码的时候,有时候花上几秒的时候来请求百度的服务器,最后展示分享按钮。

其实,像这样对网页来说不是非常重要的功能,我们大可以用JS来延迟加载,从而提高网页主要内容的快速加载显示。

这里分享下我的放置方式。

一、copy百度分享代码,如下:

<!-- Baidu Button BEGIN -->
<div id="bdshare" class="bdshare_t bds_tools_32 get-codes-bdshare">
<a class="bds_tsina"></a>
<a class="bds_qzone"></a>
<a class="bds_tqq"></a>
<a class="bds_renren"></a>
<a class="bds_douban"></a>
<span class="bds_more"></span>
<a class="shareCount"></a>
</div>
<script type="text/javascript" id="bdshare_js" data="type=tools&uid=0" ></script>
<script type="text/javascript" id="bdshell_js"></script>
<script type="text/javascript">
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000)
</script>
<!-- Baidu Button END -->

 二、放置代码

认真分析上面的分享代码,我们可以发现,其中有3个js脚本标签,这些都是有可能影响网页呈现速度的,最后发现,其实,只有最后一个<script>标签的作用是请求百度服务器,展示分享图片和链接。那么,这条JS我们大可放到最后加载。

下面是我做的一个demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<title>JS延迟加载百度分享代码,提高网页速度</title>
		<meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
		<style type="text/css">
			body{margin:0px;padding:0px;font-size:12px;}
			#copyright{clear:both;}
		</style>
	</head>

	<body>
		<div id="baidu-share">
			<!-- Baidu Button BEGIN -->
			<div id="bdshare" class="bdshare_t bds_tools_32 get-codes-bdshare">
			<a class="bds_tsina"></a>
			<a class="bds_qzone"></a>
			<a class="bds_tqq"></a>
			<a class="bds_renren"></a>
			<a class="bds_douban"></a>
			<span class="bds_more"></span>
			<a class="shareCount"></a>
			</div>
			<script type="text/javascript" id="bdshare_js" data="type=tools&uid=0" ></script>
			<script type="text/javascript" id="bdshell_js"></script>
			<!-- Baidu Button END -->
		</div>
		<div id="copyright">
			<a href="http://">编程图书PDF下载【】</a>
		</div>

		<script type="text/javascript">
			window.onload = shareCode;
			
			function shareCode(){
				document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000);
			}
		</script>
	</body>
</html>

 分析:通过上面的demo,可以发现我只是单纯的将最后一个有src属性的script标签,放到最后动态加载的,并且是在window.onload之后加载。之前加载的都是纯html标签代码,并不会有多影响网页速度。

百度分享代码通过这样调整后就算百度的服务器挂了,也不会影响自己的网页正常显示。

其实,这样的技巧还有很多地方都可以用。想网站统计代码、百度谷歌搜索代码、第三方广告代码等,我们都可以放到网页底部最后来加载,这样即使第三方的服务器宕机,我们自己的机器也不会受到多少影响。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多