Skip to content

Instantly share code, notes, and snippets.

@jpvincent
Created October 28, 2016 18:18
Show Gist options
  • Save jpvincent/51321638dee74e2dd8f53bada8a47ee5 to your computer and use it in GitHub Desktop.
Save jpvincent/51321638dee74e2dd8f53bada8a47ee5 to your computer and use it in GitHub Desktop.
inclusion asynchrone de JS prenant en compte IE < 10 et ne ralentissant pas le body.onload
// Pour rappel, voici la manière de faire de GA
/*(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');
*/
// C'est compatible partout et asynchrone, mais dans le cas de IE < 10, si le script est déclenché trop tôt, il ralentit window.onload
// Il faut donc juste écouter window.onload et déclencher ce script en asynchrone, quitte à le ralentir
function includeGa(){
(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');
}
window.addEventListener('load', function() {
setTimeout( includeGa, 0)
}, false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment