Skip to content

Instantly share code, notes, and snippets.

@yuki2021
Last active June 21, 2024 12:31
Show Gist options
  • Save yuki2021/bf0a5f85006da8413189fd8806e1d85a to your computer and use it in GitHub Desktop.
Save yuki2021/bf0a5f85006da8413189fd8806e1d85a to your computer and use it in GitHub Desktop.
遅延読み込みでGoogleアドセンスのインフィード広告を読み込み、なおかつ配信されてこない時は削除するスクリプト
<!-- Googleアドセンスのinsのdata-ad-statusがunfilledの時はnone -->
<style>
ins[data-ad-status="unfilled"] {
display: none;
}
</style>
<!-- 広告読み込み -->
<script>
(function(){
if (typeof(Ads) == 'undefined') Ads = {};
Ads.Infeed = {
content : '<center><ins class="adsbygoogle infeed_slot" style="display:block" data-ad-format="fluid" data-ad-layout="image-middle" data-ad-client="ca-pub-**********" data-ad-layout-key="**********" data-ad-slot="*********"></ins><hr /></center>',
num : 3,
disp: function(){
var self = Ads.Infeed;
var _entrySelector = 'div.entry-list a';
// PC版ページの場合のセレクター設定
if(document.querySelectorAll("div#footer-menu a.pcpage").length === 0 ) {
_entrySelector = 'div.archive-entries section';
}
var _entrys = document.querySelectorAll(_entrySelector);
var i = 0;
// 3つごとに広告を挿入
_entrys.forEach(function(entry){
if(Math.floor(i % self.num) == 0){
var adContainer = document.createElement("div");
adContainer.setAttribute("class", "list-entry-article");
adContainer.innerHTML = self.content;
entry.insertAdjacentElement('afterend', adContainer);
insertAd(adContainer);
}
i++;
});
}
}
// 広告スロットを挿入し、監視を開始する関数
function insertAd(adContainer) {
var adSlot = adContainer.querySelector('ins.adsbygoogle');
if (adSlot) {
// Google AdSenseの広告を表示
(adsbygoogle = window.adsbygoogle || []).push({});
// 広告の読み込みを監視
observeAdLoad(adContainer, adSlot);
}
}
// 広告スロットの属性変更を監視する関数
function observeAdLoad(adContainer, adSlot) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'data-ad-status') {
var adStatus = adSlot.getAttribute('data-ad-status');
if (adStatus === 'unfilled') {
// data-ad-statusがunfilledの場合は表示をnoneにし、後で削除
adSlot.style.display = 'none';
checkEmptyAd(adContainer, adSlot);
}
// 監視を停止
observer.disconnect();
}
});
});
// data-ad-status属性の変更を監視
observer.observe(adSlot, { attributes: true });
}
// 広告スロットが非表示または空の場合に広告コンテナを削除する関数
function checkEmptyAd(adContainer, adSlot) {
// 一定時間後に広告コンテナが空かどうかを確認し、空なら削除
setTimeout(function() {
if (adSlot.style.display === 'none' || adSlot.innerHTML.trim() === '') {
adContainer.remove();
}
}, 1000); // 1秒後にチェック
}
jQuery(function ($) {
var add_script = `<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-*************" crossorigin="anonymous"><\/script>`;
var lazyload_check = 'not_yet';
var lazyloadTimeout = null;
// ページロード時の遅延読み込み処理
$(window).on('load', function() {
if ('not_yet' === lazyload_check) {
lazyloadTimeout = setTimeout(onLazyLoad, 3000);
}
if ($(window).scrollTop()) {
onLazyLoad();
}
});
// スクロール、マウス移動、クリック、キー押下、タッチ開始イベントに応じて遅延読み込み処理を開始
$(window).on('scroll', onLazyLoad);
$(window).on('mousemove', onLazyLoad);
$(window).on('mousedown', onLazyLoad);
$(window).on('keydown', onLazyLoad);
window.addEventListener('touchstart', onLazyLoad);
function onLazyLoad() {
if ('not_yet' === lazyload_check) {
lazyload_check = 'already';
$(window).off('scroll', onLazyLoad);
$(window).off('mousemove', onLazyLoad);
$(window).off('mousedown', onLazyLoad);
$(window).off('keydown', onLazyLoad);
window.removeEventListener('touchstart', onLazyLoad);
$('body').append(add_script);
clearTimeout(lazyloadTimeout);
// 初期化スクリプトが呼び出された後に広告を表示
Ads.Infeed.disp();
}
}
});
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment