Google 広告 と アナリティクス を 遅延読み込みする。
マウスの動きに反応があったら、読み込む。
(function(window, document) {
function main() {
var ad = document.createElement('script');
ad.type = 'text/javascript';
ad.async = true;
ad.dataset.adClient = 'ca-pub-XXXXXXXXXXXXXXXX';
ad.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
var sc = document.getElementsByTagName('script')[0];
sc.parentNode.insertBefore(ad, sc);
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXXX-1';
//var sc = document.getElementsByTagName('script')[0];
ga.onload = function() {
console.log("ga.onload");
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXXX-1');
};
sc.parentNode.insertBefore(ga, sc);
}
// 遅延読込み
var lazyLoad = false;
function onLazyLoad() {
if (lazyLoad === false) {
lazyLoad = true;
window.removeEventListener('scroll', onLazyLoad);
window.removeEventListener('mousemove', onLazyLoad);
window.removeEventListener('mousedown', onLazyLoad);
window.removeEventListener('touchstart', onLazyLoad);
window.removeEventListener('keydown', onLazyLoad);
main();
}
}
window.addEventListener('scroll', onLazyLoad);
window.addEventListener('mousemove', onLazyLoad);
window.addEventListener('mousedown', onLazyLoad);
window.addEventListener('touchstart', onLazyLoad);
window.addEventListener('keydown', onLazyLoad);
window.addEventListener('load', function() {
if (window.pageYOffset) {
onLazyLoad();
}
});
})(window, document);