PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 1.9.5
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v1.9.5
4.1.16 4.1.15 4.1.14 4.1.13 4.1.12 4.1.11 4.1.10 4.0.30 4.0.29 4.0.28 4.0.27 4.0.26 4.0.24 4.0.25 4.0.23 4.0.22 4.0.21 4.0.19 4.0.18 4.0.17 4.0.16 1.9.3 1.9.4 1.9.5 1.9.6 All 170 releases
searchpro / inc / photon / class-scriptOptimizer.php

class-scriptOptimizer.php in BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript 1.9.5, at inc/photon/class-scriptOptimizer.php

818 lines 36.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 class berqScriptOptimizer {
4 public $loading = 'delay';
5 public $js_mode = '';
6
7 function set_loading($loading)
8 {
9 $this->loading = $loading;
10 }
11
12 function run_optimization($photonClass, $buffer) {
13
14 /* if ($this->loading == 'default') { */
15 /* return $buffer; */
16 /* } */
17
18 $this->js_mode = $photonClass->js_mode;
19
20 // Combine patterns to extract script src attributes and inline script contents
21 $pattern = '/<script\b[^>]*?(?:src=["\'](.*?)["\']|>(.*?)<\/script>)/is';
22 preg_match_all($pattern, $buffer, $matches, PREG_SET_ORDER);
23
24 // Initialize arrays for script sources and inline scripts
25 $scripts = [];
26
27 // Process the matches
28 foreach ($matches as $match) {
29 if (!empty($match[1])) {
30 // Matched script src attribute
31 if (!str_contains($match[0], 'data-berqwp')) {
32 $src = $match[1];
33 $scripts[] = $src;
34 }
35 } elseif (!empty($match[2])) {
36 // Matched inline script content
37 if (!str_contains($match[0], 'data-berqwp')) {
38 $script = $match[2];
39 $scripts[] = $script;
40 }
41 }
42
43 unset($match);
44 }
45
46 // Define the regular expression pattern for inline and external script tags
47 $pattern = '/(<script\b[^>]*>(.*?)<\/script>)/is';
48 $deffer_js = '';
49
50 // Replace with cdn script urls when they're ready
51 $script_tags_to_replace = [];
52
53 // Remove JavaScript using preg_replace_callback
54 $buffer = preg_replace_callback($pattern, function ($matches) use (&$photonClass, &$script_tags_to_replace) {
55 $tag = $matches[0];
56
57 if (strpos($tag, 'document.write(') !== false) {
58 return $tag; // Keep the script tag with id="berqWP"
59 }
60
61 // Create a Simple HTML DOM object
62 $html = str_get_html($tag);
63
64 // Find all script tags
65 foreach ($html->find('script') as $scriptTag) {
66 if (!empty($scriptTag->type) && $scriptTag->type !== 'text/javascript' && $scriptTag->type !== 'application/javascript' && $scriptTag->type !== 'module') {
67
68 return $tag;
69 }
70
71 }
72
73 $tag = $html->save();
74
75 // Clear Simple HTML DOM object
76 $html->clear();
77 unset($html);
78
79
80 if ($photonClass->use_cdn) {
81
82 // Create a Simple HTML DOM object
83 $html = str_get_html($tag);
84
85 // Find all script tags
86 foreach ($html->find('script') as $scriptTag) {
87 $src = $scriptTag->src;
88
89 $kw_found = false;
90
91 foreach ($photonClass->external_js_excluded_keywords as $keyword) {
92 if (stripos($src, $keyword) !== false) {
93 $kw_found = true;
94 }
95 }
96
97 // Check if the script source contains any excluded keywords
98 if (!$kw_found) {
99 // Use wp_remote_get to fetch the script content
100 $response = wp_remote_get($src);
101
102 if (!is_wp_error($response)) {
103 $scriptContent = wp_remote_retrieve_body($response);
104
105 // Send the file URL to CDN as GET parameters
106 /* $cdnUrl = 'https://cdn.berqwp.com/'; */
107
108 global $berqCDN;
109 $berqCDN->add_file_in_queue($src);
110
111 // $cdnUrl = 'https://boost.berqwp.com/photon/cdn/';
112 // $cdnUrl .= '?url=' . urlencode($src);
113 // $cdnUrl .= '&domain=' . $photonClass->domain;
114
115 // $photonClass->add_into_cdn_queue($cdnUrl, $src);
116
117 }
118 }
119 }
120
121 $tag = $html->save();
122
123 // Clear Simple HTML DOM object
124 $html->clear();
125 unset($html);
126
127 }
128
129 // Return the script tag after optimizing with CDN
130 if (strpos($tag, 'data-berqwp') !== false) {
131 return $tag; // Keep the script tag with id="berqWP"
132 }
133
134 if ($this->loading == 'default') {
135 return $tag;
136 }
137
138 // If tag has a match for exclude url list
139 if (!empty($photonClass->js_css_exclude_urls)) {
140 foreach ($photonClass->js_css_exclude_urls as $js_exclude_keyword) {
141 if (!empty($js_exclude_keyword)) {
142 if (strpos($tag, $js_exclude_keyword) !== false) {
143 return $tag;
144 }
145 }
146 }
147 }
148
149 if ($photonClass->js_mode == 1) {
150 $html = str_get_html($tag);
151
152 // Find all script tags
153 foreach ($html->find('script') as $scriptTag) {
154
155 if (empty($scriptTag->type) || $scriptTag->type == 'text/javascript') {
156 $scriptTag->setAttribute('data-type', 'text/javascript');
157 $scriptTag->type = 'text/bwp-script';
158 } else {
159 $scriptTag->setAttribute('data-type', esc_attr($scriptTag->type));
160 $scriptTag->type = 'text/bwp-script';
161 }
162
163 }
164
165
166 // Clear Simple HTML DOM object
167 $tag = $html->save();
168 $html->clear();
169 unset($html);
170
171 return $tag;
172 }
173
174 if ($photonClass->js_mode == 0) {
175
176 if ($photonClass->cache_js && !$photonClass->use_cdn) {
177 $tag = $photonClass->optimize_external_js($tag);
178 }
179
180 $tag_src = $photonClass->get_src_from_script($tag);
181
182
183 if (!empty($tag_src) && $photonClass->use_cdn) {
184 $script_tags_to_replace[] = $tag;
185 }
186
187 $tag = base64_encode($tag);
188
189
190
191 return '<script data-berqwp-js="' . esc_attr($tag) . '"></script>'; // Remove other script tags
192
193 } elseif ($photonClass->js_mode == 2) {
194
195 if ($photonClass->cache_js && !$photonClass->use_cdn) {
196 return $photonClass->optimize_external_js($tag);
197 } else {
198 return $tag;
199 }
200
201 }
202 }, $buffer);
203
204 // if ($photonClass->use_cdn) {
205
206 // $cdn_file_responses = $photonClass->parallelCurlRequests($photonClass->cdn_upload_queue, [], 'GET');
207 // for ($i = 0; $i < count($cdn_file_responses); $i++) {
208
209 // $original_file = $photonClass->original_files_for_cdn[$i];
210 // $cdnData = json_decode($cdn_file_responses[$i]);
211
212 // if ($cdnData && isset($cdnData->status) && $cdnData->status === 'success' && isset($cdnData->filePath)) {
213 // // Use the CDN file path in your WordPress code
214 // $cdnFilePath = $cdnData->filePath;
215 // /* $cdn_file = 'https://cdn.berqwp.com' . $cdnFilePath; */
216 // $cdn_file = $cdnFilePath;
217
218 // if (($photonClass->js_mode == 1 || $photonClass->js_mode == 0) && strpos($cdn_file, '.js') !== false) {
219
220 // foreach ($script_tags_to_replace as $script_tag) {
221 // if (strpos($script_tag, $original_file) !== false) {
222
223 // $origional_tag_base64 = esc_attr(base64_encode($script_tag));
224 // $script_tag = str_replace($original_file, $cdn_file, $script_tag);
225 // $tag = esc_attr(base64_encode($script_tag));
226
227 // $buffer = str_replace($origional_tag_base64, $tag, $buffer);
228
229 // }
230 // }
231 // // $original_file = base64_encode($original_file);
232 // // $cdn_file = base64_encode($cdn_file);
233 // }
234
235 // $buffer = str_replace($original_file, $cdn_file, $buffer);
236 // }
237
238
239 // }
240 // }
241
242 if ($this->loading !== 'default') {
243 add_filter('berqwp_buffer_before_closing_body', [$this, 'script']);
244
245 }
246
247 unset($photonClass);
248
249 return $buffer;
250 }
251
252 function script($script_html) {
253 $script_html .= "
254 <script id='create-blob'>
255 // Get all script tags in the document
256 var scriptTags = document.getElementsByTagName('script');
257
258 // Loop through each script tag
259 for (let i = 0; i < scriptTags.length; i++) {
260 const scriptTag = scriptTags[i];
261
262 // Check if the script tag contains the data-berqwp-js attribute
263 const berqwpAttribute = scriptTag.getAttribute('data-berqwp-js');
264 if (berqwpAttribute) {
265 // Decode the base64 encoded string
266 const decodedString = atob(berqwpAttribute);
267
268 // Extract the inner content of the decoded string
269 const match = decodedString.match(/<script[^>]*>([\s\S]+)<\/script>/i);
270 if (match && match.length > 1) {
271 const innerContent = match[1];
272
273 // Convert the inner content into a Blob
274 const blob = new Blob([innerContent], { type: 'application/javascript' });
275
276 // Create a new script tag with the blob content
277 const newScriptTag = document.createElement('script');
278 newScriptTag.src = URL.createObjectURL(blob);
279 console.log(URL.createObjectURL(blob))
280
281 // Convert the newScriptTag HTML string to base64
282 const newScriptTagHtml = newScriptTag.outerHTML;
283 const base64Encoded = btoa(newScriptTagHtml);
284
285 // Add the base64 encoded string back to the data-berqwp-js attribute of the original script tag
286 scriptTag.setAttribute('data-berqwp-js', base64Encoded);
287 }
288 }
289 }
290
291 </script>
292 ";
293
294 $script_html .= "
295 <script type='text/javascript' defer>
296 (function() {
297 window.addEventListener('berqwpLCPLoaded', function () {
298 // Create the worker from the inline script
299 var blob = new Blob([`
300 var preloadRequests = 0;
301 var remainingCount = {};
302 var baseURI = '';
303
304 self.onmessage = function(e) {
305 switch(e.data.cmd) {
306 case 'RESOURCE_PRELOAD':
307 var requestId = e.data.requestId;
308 remainingCount[requestId] = 0;
309
310 e.data.resources.forEach(function(resource) {
311 preload(resource, function() {
312 return function() {
313 console.log(requestId + ' DONE: ' + resource);
314 if (--remainingCount[requestId] == 0) {
315 self.postMessage({cmd: 'RESOURCE_PRELOAD', requestId: requestId});
316 }
317 }
318 }(requestId));
319 remainingCount[requestId]++;
320 });
321 break;
322 case 'SET_BASEURI':
323 baseURI = e.data.uri;
324 break;
325 }
326 };
327
328 async function preload(resource, callback) {
329 if (typeof URL !== 'undefined' && baseURI) {
330 try {
331 var url = new URL(resource, baseURI);
332 resource = url.href;
333 } catch (error) {
334 console.log('Worker error: ' + error.message);
335 }
336 }
337
338 console.log('Preloading and caching ' + resource);
339
340 try {
341 // Open or create the cache named 'berqwp-cache'
342 const cache = await caches.open('berqwp-cache');
343
344 // Fetch the resource
345 const request = new Request(resource, { mode: 'no-cors', redirect: 'follow' });
346 const response = await fetch(request);
347
348 if (response.ok) {
349 // Add the fetched resource to the cache
350 await cache.put(resource, response.clone());
351 console.log('Resource cached:', resource);
352 }
353
354 callback();
355 } catch (error) {
356 console.log(error);
357
358 var xhr = new XMLHttpRequest();
359 xhr.responseType = 'blob';
360 xhr.onload = callback;
361 xhr.onerror = callback;
362 xhr.open('GET', resource, true);
363 xhr.send();
364 }
365 }
366 `], { type: 'application/javascript' });
367
368 var worker = new Worker(URL.createObjectURL(blob));
369
370 // Set the base URI if necessary
371 worker.postMessage({
372 cmd: 'SET_BASEURI',
373 uri: document.baseURI
374 });
375
376 // Collect external script URLs (excluding inline scripts)
377 var externalScripts = Array.from(document.querySelectorAll('script[src]'))
378 .map(script => script.src);
379
380 // Send the list of external scripts to the worker for preloading and caching
381 worker.postMessage({
382 cmd: 'RESOURCE_PRELOAD',
383 requestId: '',
384 resources: externalScripts
385 });
386
387 worker.onmessage = function(e) {
388 if (e.data.cmd === 'RESOURCE_PRELOAD') {
389 console.log('All resources for ' + e.data.requestId + ' are preloaded and cached.');
390 }
391 };
392
393 });
394
395 })();
396 </script>
397 ";
398
399
400 $script_html .= "
401 <script id='optimize-js' defer>
402 let js_execution_mode = '" . $this->js_mode . "';
403 let js_loading = '" . $this->loading . "';
404 let berq_content;
405 let berq_click = null;
406 var total_berq_scripts = 0;
407 var loaded_berq_scripts = 0;
408 let assets_to_cache = [];
409
410 var scriptTags = document.querySelectorAll('script[data-berqwp-js]');
411 scriptTags.forEach(div => {
412 const scriptData = atob(div.getAttribute('data-berqwp-js'));
413 const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
414
415 if (scriptElement.src) {
416 total_berq_scripts++;
417 }
418
419 });
420
421 let lcpElement = null;
422 const lcp_observer = new PerformanceObserver((list) => {
423 const entries = list.getEntries();
424 for (const entry of entries) {
425 if (entry.entryType === 'largest-contentful-paint') {
426 lcpElement = entry.element;
427
428 // If the LCP element has a background image
429 const backgroundImage = window.getComputedStyle(lcpElement).backgroundImage;
430
431 if (backgroundImage && backgroundImage !== 'none') {
432 // Extract the URL from the background-image CSS property
433 const imageUrl = backgroundImage.slice(5, -2);
434
435 // Create a new Image object to check if the background image is loaded
436 const img = new Image();
437 img.src = imageUrl;
438
439 img.onload = function() {
440 console.log('Background image loaded:', imageUrl);
441 let berqwp_lcp_event = new CustomEvent('berqwpLCPLoaded');
442 window.dispatchEvent(berqwp_lcp_event);
443 };
444
445 img.onerror = function() {
446 console.error('Failed to load background image:', imageUrl);
447 };
448 } else {
449 // If there's no background image or it's already loaded
450 let berqwp_lcp_event = new CustomEvent('berqwpLCPLoaded');
451 window.dispatchEvent(berqwp_lcp_event);
452 }
453 }
454 }
455 });
456
457 lcp_observer.observe({ type: 'largest-contentful-paint', buffered: true });
458
459 // let lcpElement = null;
460 // const lcp_observer = new PerformanceObserver((list) => {
461 // const entries = list.getEntries();
462 // for (const entry of entries) {
463 // if (entry.entryType === 'largest-contentful-paint') {
464 // lcpElement = entry.element;
465
466 // console.log(lcpElement)
467
468 // // Check if LCP element is already loaded
469 // if (lcpElement.complete) {
470 // let berqwp_lcp_event = new CustomEvent('berqwpLCPLoaded');
471 // window.dispatchEvent(berqwp_lcp_event);
472 // }
473 // }
474 // }
475 // });
476
477 // lcp_observer.observe({ type: 'largest-contentful-paint', buffered: true });
478
479 // Preload scrpits right after LCP images
480 window.addEventListener('berqwpLCPLoaded', function () {
481 if (js_execution_mode == '1') {
482
483 var scripts = document.querySelectorAll('script[type=\"text/bwp-script\"]');
484 let assets_to_cache = [];
485
486 // Add all external scripts into browser cache
487 scripts.forEach(scriptElement => {
488 if (scriptElement.src) {
489 assets_to_cache.push(scriptElement.src);
490 }
491 });
492
493 // (async () => {
494 // await berqwp_add_assets_browser_cache(assets_to_cache);
495 // })();
496 }
497 })
498
499
500
501 function berqwp_js_handleUserInteraction(event) {
502
503 if (event.type === 'click' || event.type === 'touchstart') {
504 event.preventDefault();
505 berq_click = event.target;
506 }
507
508 if (js_execution_mode == 0) {
509 // Get all script tags with data-berqwp-js attribute
510 var scriptTags = document.querySelectorAll('script[data-berqwp-js]');
511
512 // Add all external scripts into browser cache
513 scriptTags.forEach(div => {
514 const scriptData = atob(div.getAttribute('data-berqwp-js'));
515 const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
516
517 if (scriptElement && scriptElement.src) {
518 assets_to_cache.push(scriptElement.src);
519 }
520 });
521
522 (async () => {
523 // Call the function to start fetching all scripts
524 await berqwp_add_assets_browser_cache(assets_to_cache);
525
526 // Function to execute scripts
527 function executeScriptsSequentially(scripts, index) {
528 if (index < scripts.length) {
529 var scriptTag = scripts[index];
530 var berqwpJsCode = scriptTag.getAttribute('data-berqwp-js');
531 berqwpJsCode = atob(berqwpJsCode);
532 var parser = new DOMParser();
533 var parsedHTML = parser.parseFromString(berqwpJsCode, 'text/html');
534 var scriptContent = parsedHTML.querySelector('script');
535
536 if (scriptContent) {
537 if (scriptContent.src) {
538 // External script, append to the body
539 var newScript = document.createElement('script');
540 newScript.onload = function () {
541 // Execute the next script in the sequence
542 executeScriptsSequentially(scripts, index + 1);
543 loaded_berq_scripts++;
544 };
545 newScript.src = scriptContent.src;
546
547 // console.log(newScript.src)
548 // document.body.appendChild(newScript);
549 scriptTag.parentNode.insertBefore(newScript, scriptTag.nextSibling);
550
551 } else {
552 var newScript = document.createElement('script');
553 newScript.innerHTML = scriptContent.innerHTML;
554
555 // console.log(newScript);
556 // document.body.appendChild(newScript);
557 scriptTag.parentNode.insertBefore(newScript, scriptTag.nextSibling);
558
559 // Inline script, execute immediately
560 // eval(scriptContent.innerHTML);
561 // Execute the next script in the sequence
562 executeScriptsSequentially(scripts, index + 1);
563 }
564 }
565 }
566 }
567
568 // Start executing scripts sequentially
569 executeScriptsSequentially(scriptTags, 0);
570
571 berq_content = true;
572
573 })();
574
575
576
577 } else if (js_execution_mode == 1) {
578 let bwp_independent_scripts = ['googletagmanager.com/gtag', 'cdn-cookieyes.com/client_data', 'static.getclicky.com', 'clarity.ms/', 'google.com', 'doubleclick.net', 'stats.wp.com'];
579 var scripts = document.querySelectorAll('script[type=\"text/bwp-script\"]');
580
581 // Function to dynamically load scripts
582 function loadScript(index) {
583 if (index >= scripts.length) {
584 // After all scripts are loaded, dispatch events
585 let event = new Event('DOMContentLoaded', {
586 bubbles: true,
587 cancelable: true
588 });
589 document.dispatchEvent(event);
590 window.dispatchEvent(new Event('load'));
591
592 // Create a new resize event
593 var resizeEvent = new Event('resize');
594
595 // Dispatch the resize event
596 window.dispatchEvent(resizeEvent);
597
598 console.log('scripts loaded.')
599 return;
600 }
601
602 // Create a new script element
603 var script = scripts[index];
604 var newScript = document.createElement('script');
605 // newScript.type = 'text/javascript';
606 newScript.type = script.getAttribute('data-type');
607
608 // Copy the content or src of the original script
609 if (script.src) {
610 newScript.src = script.src;
611
612 let includesItem = bwp_independent_scripts.some(item => script.src.includes(item));
613
614 if (includesItem) {
615 loadScript(index + 1);
616 } else {
617
618 // Set a timeout to proceed even if onload doesn't fire
619 var scriptTimeout = setTimeout(function() {
620 console.warn('Script load timeout:', script.src);
621 loadScript(index + 1);
622 }, 5000); // 5 seconds timeout
623
624
625 newScript.onload = function() {
626 clearTimeout(scriptTimeout); // Clear timeout if script loads successfully
627 loadScript(index + 1);
628 };
629
630 newScript.onerror = function() {
631 clearTimeout(scriptTimeout); // Clear timeout if there's an error loading the script
632 console.warn('Error loading script:', script.src);
633 loadScript(index + 1); // Proceed to the next script
634 };
635 }
636
637
638 } else {
639 newScript.text = script.textContent;
640 setTimeout(function() {
641 loadScript(index + 1);
642 }, 0); // Delay to simulate async load
643 }
644
645 // Copy other attributes if necessary
646 Array.from(script.attributes).forEach(function(attr) {
647 if (attr.name !== 'type') {
648 newScript.setAttribute(attr.name, attr.value);
649 }
650 });
651
652 // Replace the old script with the new script
653 script.parentNode.replaceChild(newScript, script);
654 }
655
656 // Add all external scripts into browser cache
657 scripts.forEach(scriptElement => {
658 if (scriptElement.src) {
659 let includesItem = bwp_independent_scripts.some(item => scriptElement.src.includes(item));
660
661 if (!includesItem) {
662 assets_to_cache.push(scriptElement.src);
663 }
664 }
665 });
666
667 (async () => {
668 await berqwp_add_assets_browser_cache(assets_to_cache);
669
670 // Start loading scripts from the first one
671 loadScript(0);
672
673 })();
674
675
676 // const divs = document.querySelectorAll('script[data-berqwp-js]');
677
678 // // Add all external scripts into browser cache
679 // divs.forEach(div => {
680 // const scriptData = atob(div.getAttribute('data-berqwp-js'));
681 // const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
682
683 // if (scriptElement && scriptElement.src) {
684 // assets_to_cache.push(scriptElement.src);
685 // }
686 // });
687
688 // (async () => {
689 // // Call the function to start fetching all scripts
690 // await berqwp_add_assets_browser_cache(assets_to_cache);
691
692 // divs.forEach(div => {
693 // const scriptData = atob(div.getAttribute('data-berqwp-js'));
694 // const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
695 // if (scriptElement) {
696
697 // // Set the onload event handler for the script element
698 // scriptElement.onload = function() {
699 // loaded_berq_scripts++;
700 // };
701
702 // // document.body.appendChild(scriptElement);
703 // // div.insertAdjacentHTML('afterend', scriptElement);
704 // // scriptElement.setAttribute('async', 'false');
705 // // div.parentNode.insertBefore(scriptElement, div.nextSibling);
706
707 // setTimeout(function() {
708 // div.parentNode.insertBefore(scriptElement, div.nextSibling);
709
710 // }, 100)
711 // }
712 // });
713
714
715 // berq_content = false;
716 // setTimeout(function () {
717
718 // let event = new Event('DOMContentLoaded', {
719 // bubbles: true,
720 // cancelable: true
721 // });
722 // document.dispatchEvent(event);
723 // window.dispatchEvent(new Event('load'));
724
725
726 // // Create a new resize event
727 // var resizeEvent = new Event('resize');
728
729 // // Dispatch the resize event
730 // window.dispatchEvent(resizeEvent);
731
732 // }, 1000);
733
734 // })();
735
736
737
738 }
739
740
741
742 // After running the function, remove all event listeners to ensure it runs only once
743 for (let eventType of berqwp_js_interactionEventTypes) {
744 window.removeEventListener(eventType, berqwp_js_handleUserInteraction);
745 }
746 }
747
748 let berqwp_js_interactionEventTypes = ['click', 'mousemove', 'keydown', 'touchstart', 'scroll', 'berqwpLoadJS', 'berqwp_interaction_event'];
749
750 if (js_loading == 'preload') {
751 berqwp_js_interactionEventTypes = ['berqwpStylesLoaded'];
752
753 // berqwp_js_interactionEventTypes.push('berqwpStylesLoaded');
754 }
755
756 for (let eventType of berqwp_js_interactionEventTypes) {
757 window.addEventListener(eventType, berqwp_js_handleUserInteraction, { passive: false });
758 }
759
760 if (js_loading == 'preload' && !document.getElementById('preload-styles')) {
761 // Trigger event to load JavaScript
762 let berqwp_load_js_event = new CustomEvent('berqwpLoadJS');
763
764 // Dispatch the custom event
765 window.dispatchEvent(berqwp_load_js_event);
766 }
767
768 setInterval(function () {
769
770 if (berq_content == true) {
771 berq_content = false;
772 let event = new Event('DOMContentLoaded', {
773 bubbles: true,
774 cancelable: true
775 });
776 document.dispatchEvent(event);
777 window.dispatchEvent(new Event('load'));
778
779
780 // Create a new resize event
781 var resizeEvent = new Event('resize');
782
783 // Dispatch the resize event
784 window.dispatchEvent(resizeEvent);
785
786
787
788 }
789
790 if (berq_click && total_berq_scripts == loaded_berq_scripts) {
791 setTimeout(function() {
792 console.log(berq_click);
793 const clickEvent = new MouseEvent('click', {
794 bubbles: true,
795 cancelable: true,
796 view: window
797 });
798 berq_click.dispatchEvent(clickEvent);
799 berq_click = null;
800 }, 500)
801 }
802
803 }, 2000);
804
805 var berq_timeo;
806 if (window.screen.width <= 999) {
807 berq_timeo = 3000;
808 } else {
809 berq_timeo = 4000;
810 }
811
812 </script>
813 ";
814
815 return $script_html;
816 }
817 }
818