PageSourceSearch

https://grad.ua/templates/Grad-2023/js/banner_google.js?v=015

js grad.ua collected 2026-10-02 05:35:27 UTC 7,331 bytes, 178 lines download raw bytes

1/**
2 * Комплексный скрипт динамической вставки Google AdSense.
3 * Включает: ленивую загрузку, абсолютную математику прилипания и слежение за изменением DOM.
4 * Версия синтаксиса адаптирована для старых редакторов кода.
5 */
6window.addEventListener('load', function() {
7    
8    console.log('Шаг 1: Скрипт инициализирован.');
9
10    // 1. Отключаем работу на смартфонах и планшетах
11    if (window.innerWidth < 992) {
12        console.log('Остановка: Мобильное устройство.');
13        return; 
14    }
15
16    // 2. Ищем основные контейнеры страницы
17    const mainContent = document.querySelector('.content');
18    const widgetArea = document.querySelector('.widget-area');
19
20    if (!mainContent) console.error('Ошибка: не найдена левая колонка (.content)');
21    if (!widgetArea) console.error('Ошибка: не найдена область виджетов (.widget-area)');
22    if (!mainContent || !widgetArea) return;
23
24    // Флаг, блокирующий повторную вставку рекламы
25    let isBannerInserted = false;
26
27    /**
28     * Главная логическая функция: проверяет место и вставляет баннер.
29     */
30    function tryInsertBanner() {
31        if (isBannerInserted) return;
32
33        const emptySpace = mainContent.offsetHeight - widgetArea.offsetHeight;
34        console.log('Шаг 2: Анализ высоты. Свободно: ' + emptySpace + 'px');
35
36        let adSlotId = '';
37        let adFormat = '';
38
39        if (emptySpace >= 650) {
40            console.log('Шаг 3: Выбран БОЛЬШОЙ баннер (300x600).');
41            adSlotId = '3411197132';
42            adFormat = 'display:inline-block;width:100%;height:600px;';
43        } else if (emptySpace >= 300) {
44            console.log('Шаг 3: Выбран МАЛЫЙ баннер (300x250).');
45            adSlotId = '3175302174';
46            adFormat = 'display:inline-block;width:100%;height:250px;';
47        } else {
48            console.log('Ожидание: Недостаточно пустого пространства.');
49            return; 
50        }
51
52        console.log('Шаг 4: Генерируем HTML код баннера...');
53        const bannerElement = insertAdSenseWidget(widgetArea, adSlotId, adFormat);
54        isBannerInserted = true;
55
56        console.log('Шаг 5: Запускаем математический алгоритм прилипания.');
57        initJSSticky(bannerElement, mainContent);
58    }
59
60    // ТРИГГЕР №1: Скролл до виджетов
61    const scrollObserver = new IntersectionObserver(function(entries) {
62        entries.forEach(function(entry) {
63            if (entry.isIntersecting) {
64                console.log('Сработал Триггер №1: Пользователь видит конец сайдбара.');
65                tryInsertBanner();
66            }
67        });
68    }, { rootMargin: '200px' }); 
69
70    const lastWidget = widgetArea.lastElementChild;
71    if (lastWidget) {
72        scrollObserver.observe(lastWidget);
73    } else {
74        tryInsertBanner(); 
75    }
76
77    // ТРИГГЕР №2: Изменение высоты левой колонки
78    if (typeof ResizeObserver !== 'undefined') {
79        const resizeObs = new ResizeObserver(function() {
80            if (!isBannerInserted) {
81                const widgetRect = widgetArea.getBoundingClientRect();
82                if (widgetRect.bottom <= window.innerHeight + 500) {
83                    console.log('Сработал Триггер №2: Изменился размер контента!');
84                    tryInsertBanner();
85                }
86            }
87        });
88        resizeObs.observe(mainContent); 
89    }
90});
91
92/**
93 * Создает узел DOM, наполняет его разметкой AdSense.
94 * ВАЖНО: Использована классическая конкатенация строк (склеивание плюсами).
95 */
96function insertAdSenseWidget(targetContainer, slotId, formatStyles) {
97    const asideWrapper = document.createElement('aside');
98    asideWrapper.setAttribute('align', 'center');
99    asideWrapper.style.marginTop = '5px'; 
100    asideWrapper.style.width = '100%';
101    
102    // Склеиваем HTML-строку без использования обратных кавычек
103    asideWrapper.innerHTML = 
104        '<div class="pr-col-boottom dynamic-adsense-wrapper googleBnrs">\n' +
105        '    <span class="ad-label">Р Е К Л А М А</span>\n' +
106        '        <ins class="adsbygoogle"\n' +
107        '             style="' + formatStyles + '"\n' +
108        '             data-ad-client="ca-pub-7496871329591180"\n' +
109        '             data-ad-slot="' + slotId + '"></ins>\n' +
110        '    </span>\n' +
111        '</div>';
112
113    targetContainer.appendChild(asideWrapper);
114
115    try {
116        (window.adsbygoogle = window.adsbygoogle || []).push({});
117    } catch (error) {
118        console.warn('Google AdSense заблокирован:', error);
119    }
120    
121    return asideWrapper; 
122}
123
124/**
125 * Движок прилипания блока.
126 */
127function initJSSticky(banner, mainContent) {
128    const spacer = document.createElement('div');
129    spacer.style.display = 'none'; 
130    spacer.style.clear = 'both'; 
131    banner.parentNode.insertBefore(spacer, banner);
132
133    let isStuck = false;
134    let originalAbsoluteTop = 0;
135
136    window.addEventListener('scroll', function() {
137        if (!isStuck) {
138            originalAbsoluteTop = window.scrollY + banner.getBoundingClientRect().top;
139        }
140
141        const triggerPoint = originalAbsoluteTop - 20; 
142
143        if (window.scrollY >= triggerPoint) {
144            if (!isStuck) {
145                spacer.style.height = banner.offsetHeight + 'px';
146                spacer.style.display = 'block';
147                
148                banner.style.position = 'fixed';
149                banner.style.top = '20px';
150                banner.style.width = spacer.parentNode.offsetWidth + 'px';
151                banner.style.zIndex = '99';
152                isStuck = true;
153            }
154
155            const mainRect = mainContent.getBoundingClientRect();
156            const bannerHeight = banner.offsetHeight;
157            
158            if (mainRect.bottom < (20 + bannerHeight)) {
159                banner.style.top = (mainRect.bottom - bannerHeight) + 'px';
160            } else {
161                banner.style.top = '20px';
162            }
163        } else {
164            if (isStuck) {
165                spacer.style.display = 'none';
166                banner.style.position = 'static';
167                banner.style.width = '100%';
168                isStuck = false;
169            }
170        }
171    });
172
173    window.addEventListener('resize', function() {
174        if (isStuck) {
175            banner.style.width = spacer.parentNode.offsetWidth + 'px';
176        }
177    });
178}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.