现在的网站中自然少不了JS,网站特效JS,网站数据AJAX,网站广告联盟JS,网站统计JS等,所以网站打开速度就受到了很大的影响,特别是小带宽和大访问量的,所以优化好JS是可以大大提升网站打开速度,利于SEO,也利于用户体验的,今天我们就来讲讲JS和网站页面代码的分离的调用。
我们可以将所有的上面讲到的各种JS都放到一个js文件中,对各个不同的JS进行命名,然后就可以调用了 如下例子:
//百度统计JS代码
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?800c18416bc5f2b3f4e69ab42f34556d";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
//百度推送JS代码
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
//adsense 谷歌广告联盟300*600
function adsense300_600(){
document.writeln("<script async src=\'//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\'></script>");
document.writeln("<!-- 300*600 -->");
document.writeln("<ins class=\'adsbygoogle\'");
document.writeln(" style=\'display:inline-block;width:300px;height:600px\'");
document.writeln(" data-ad-client=\'ca-pub-4198413193019483\'");
document.writeln(" data-ad-slot=\'4993999683\'></ins>");
document.writeln("<script>");
document.writeln("(adsbygoogle = window.adsbygoogle || []).push({});");
document.writeln("</script>");
}
然后上面的代码中谷歌广告代码需要在网页中显示被调用,那么只需要在网页中使用如下代码进行调用:
<script>adsense728_90();</script>
这样就被调用了,而不需要把上面的一串JS每一个都添加到各个网页里了。