PHP
在你的HTML或PHP代码中添加这个:
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-PUT YOUR GOOGLE ANALYTICS ID HERE', 'auto');
ga('send', 'pageview');
</script>
<?php endif; ?>
JavaScript
这在JavaScript中工作得很好:
<script>
if(navigator.userAgent.indexOf("Speed Insights") == -1) {
(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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-<PUT YOUR GOOGLE ANALYTICS ID HERE>', 'auto');
ga('send', 'pageview');
}
</script>
NiloVelez已经说过:很明显,它不会带来任何真正的改善,但如果你唯一关心的是获得100/100的分数,它就可以做到。