推迟Javascript解析给出错误

时间:2014-08-20 20:22:24

标签: javascript jquery css performance seo

我购买了一个主题。修改了它。然而,它加载缓慢。我压缩了图像,并使用了gzip。我在某处读到推迟JS解析可能会有所帮助。所以,我使用在body标签下面添加的以下脚本推迟了它们。现在,该页面甚至不会加载。

<script type="text/javascript" charset="utf-8">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js/filename.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>

我使用的脚本列表:

<script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&language=en"></script>
    <script type="text/javascript" src="js/jquery.cookie.js"></script>
    <script type="text/javascript" src="js/styleswitch.js"></script>
    <script type="text/javascript" src="js/jquery.nav.js"></script>
    <script type="text/javascript" src="js/jquery.sticky.js"></script>
    <script type="text/javascript" src="js/jquery.parallax-1.1.3.js"></script>
    <script type="text/javascript" src="js/jquery.lavalamp-1.4.js"></script>
    <script type="text/javascript" src="js/jquery.scrollTo.js"></script>

    <script type="text/javascript" src="js/rs-plugin/js/jquery.themepunch.plugins.min.js"></script>
    <script type="text/javascript" src="js/rs-plugin/js/jquery.themepunch.revolution.min.js"></script>
    <script type="text/javascript" src="js/jquery.carouFredSel-6.1.0-packed.js"></script> 
    <script type="text/javascript" src="js/jquery.bxslider.min.js"></script>
    <script type="text/javascript" src="js/jquery.colorbox.js"></script>    
    <script type="text/javascript" src="js/jquery.isotope.min.js"></script>
    <script type="text/javascript" src="js/fancybox/jquery.fancybox.pack.js"></script>
    <script type="text/javascript" src="js/jquery.gmap.js"></script>
    <script type="text/javascript" src="js/flex-slider.min.js"></script>
    <script type="text/javascript" src="js/jquery.placeholder.js"></script>
    <script type="text/javascript" src="js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="js/jquery.tweet.js"></script>

    <script type="text/javascript" src="js/main.js" charset="utf-8"></script>

1 个答案:

答案 0 :(得分:1)

你可能意味着这样的事情:

function downloadJSAtOnload( script) {
  var element = document.createElement("script");
  element.src = script;
  document.body.appendChild(element);
}

function downloadAllScripts () {
  downloadJSAtOnload( 'js/jquery.js');
  downloadJSAtOnload( 'js/bootstrap.min.js');
  //etc
}

if (window.addEventListener)
  window.addEventListener("load", downloadAllScripts, false);
else if (window.attachEvent)
  window.attachEvent("onload", downloadAllScripts);
else window.onload = downloadAllScripts;