2015-11-20 265 views
0

我在我的网页上使用jquery malihu自定义滚动条。然后,我嵌入了谷歌分析代码剪切。有时(可能是10次中的4次),Analytics.js需要40秒才能加载。滚动条脚本是必不可少的,没有它的网站看起来很丑陋,但这个滚动条脚本在加载页面后执行。但是页面不会再加载40秒(因为analytics.js),所以它看起来像垃圾40秒。 是不是analytics.js加载异步?那么为什么它会阻止正确加载页面?Analytics.js阻止其他脚本

这是它的外观:

<!DOCTYPE html> 
<html lang="de"> 
    <head> 
    <!-- Some meta tags, links, scripts -->  
    <link rel="stylesheet" href="css/jquery.mCustomScrollbar.css"> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script src="js/jquery.mCustomScrollbar.concat.min.js"></script> 
    </head> 
    <body onload="onLoad();" > 
    <!-- Some code -->  
    <script> 
    (function($){ 
     $(window).load(function(){ 

      $("body").mCustomScrollbar({ 
       theme:"minimal-dark" 
      }); 

     }); 
    })(jQuery); 
    </script> 

    <script> 
     (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
     (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
     m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 
     })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 

     ga('create', 'UA-X4XXX297-X', 'auto'); 
     ga('send', 'pageview'); 

    </script> 
    </body> 
</html> 

回答

1

根据这个链接Analytics for Web (analytics.js),谷歌Analytics(分析)不会加载阻止其他脚本。

试图改变你的脚本文件上,而不是准备好运行:

(function($) { 
    $(window).ready(function() { 

     $("body").mCustomScrollbar({ 
      theme: "minimal-dark" 
     }); 

    }); 
})(jQuery); 
+0

可悲的是,它仍然阻止...但这与[解释]我可以解决这个问题(http://stackoverflow.com/questions/31908429/stop-analytics-code-from-blocking-other-script-execution) ... 我在滚动条脚本下方添加了一个不同的分析(在链接中找到) – noah

0

异步脚本,其中包括谷歌的analytics.js脚本,不妨碍其他脚本或渲染的加载。

什么导致mCustomScrollbar的延迟执行是它在onload事件中执行的事实。只有在下载所有资产时才会启动加载。 这包括所有脚本,图像,CSS等。

所以你有两个选择。要么不等待onloadevent,而是使用DOMContentLoaded。既然你已经在使用jQuery,你可以使用$(window).ready。我不知道jquery malihu自定义滚动条,所以你需要确保它不依赖于被完全加载的页面。

或者你需要调查什么是阻止onload事件。 因此,打开浏览器的developertools网络选项卡中的网页或打开webpagetest中的网站,并尝试找出它是什么会减慢onload事件。