PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 1.9.6
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v1.9.6
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.6, at inc/photon/class-scriptOptimizer.php

878 lines 40.0 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 $shouldSkipOnLoad = false;
156 $scriptsrc = $scriptTag->src;
157 if (!empty($scriptsrc)) {
158 foreach ($photonClass->skipOnLoadJS as $pattern) {
159 if (strpos($scriptsrc, $pattern) !== false) {
160 $shouldSkipOnLoad = true;
161 break;
162 }
163 }
164 }
165
166 if ($shouldSkipOnLoad) {
167 $scriptTag->setAttribute('data-berqwpSkipOnLoad', '1');
168 }
169
170 if (empty($scriptTag->type) || $scriptTag->type == 'text/javascript') {
171 $scriptTag->setAttribute('data-type', 'text/javascript');
172 $scriptTag->type = 'text/bwp-script';
173 } else {
174 $scriptTag->setAttribute('data-type', esc_attr($scriptTag->type));
175 $scriptTag->type = 'text/bwp-script';
176 }
177
178 }
179
180
181 // Clear Simple HTML DOM object
182 $tag = $html->save();
183 $html->clear();
184 unset($html);
185
186 return $tag;
187 }
188
189 if ($photonClass->js_mode == 0) {
190
191 if ($photonClass->cache_js && !$photonClass->use_cdn) {
192 $tag = $photonClass->optimize_external_js($tag);
193 }
194
195 $tag_src = $photonClass->get_src_from_script($tag);
196
197
198 if (!empty($tag_src) && $photonClass->use_cdn) {
199 $script_tags_to_replace[] = $tag;
200 }
201
202 $tag = base64_encode($tag);
203
204
205
206 return '<script data-berqwp-js="' . esc_attr($tag) . '"></script>'; // Remove other script tags
207
208 } elseif ($photonClass->js_mode == 2) {
209
210 if ($photonClass->cache_js && !$photonClass->use_cdn) {
211 return $photonClass->optimize_external_js($tag);
212 } else {
213 return $tag;
214 }
215
216 }
217 }, $buffer);
218
219 // if ($photonClass->use_cdn) {
220
221 // $cdn_file_responses = $photonClass->parallelCurlRequests($photonClass->cdn_upload_queue, [], 'GET');
222 // for ($i = 0; $i < count($cdn_file_responses); $i++) {
223
224 // $original_file = $photonClass->original_files_for_cdn[$i];
225 // $cdnData = json_decode($cdn_file_responses[$i]);
226
227 // if ($cdnData && isset($cdnData->status) && $cdnData->status === 'success' && isset($cdnData->filePath)) {
228 // // Use the CDN file path in your WordPress code
229 // $cdnFilePath = $cdnData->filePath;
230 // /* $cdn_file = 'https://cdn.berqwp.com' . $cdnFilePath; */
231 // $cdn_file = $cdnFilePath;
232
233 // if (($photonClass->js_mode == 1 || $photonClass->js_mode == 0) && strpos($cdn_file, '.js') !== false) {
234
235 // foreach ($script_tags_to_replace as $script_tag) {
236 // if (strpos($script_tag, $original_file) !== false) {
237
238 // $origional_tag_base64 = esc_attr(base64_encode($script_tag));
239 // $script_tag = str_replace($original_file, $cdn_file, $script_tag);
240 // $tag = esc_attr(base64_encode($script_tag));
241
242 // $buffer = str_replace($origional_tag_base64, $tag, $buffer);
243
244 // }
245 // }
246 // // $original_file = base64_encode($original_file);
247 // // $cdn_file = base64_encode($cdn_file);
248 // }
249
250 // $buffer = str_replace($original_file, $cdn_file, $buffer);
251 // }
252
253
254 // }
255 // }
256
257 if ($this->loading !== 'default') {
258 add_filter('berqwp_buffer_before_closing_body', [$this, 'script']);
259
260 }
261
262 unset($photonClass);
263
264 return $buffer;
265 }
266
267 function script($script_html) {
268 $script_html .= "
269 <script id='create-blob'>
270 // Get all script tags in the document
271 var scriptTags = document.getElementsByTagName('script');
272
273 // Loop through each script tag
274 for (let i = 0; i < scriptTags.length; i++) {
275 const scriptTag = scriptTags[i];
276
277 // Check if the script tag contains the data-berqwp-js attribute
278 const berqwpAttribute = scriptTag.getAttribute('data-berqwp-js');
279 if (berqwpAttribute) {
280 // Decode the base64 encoded string
281 const decodedString = atob(berqwpAttribute);
282
283 // Extract the inner content of the decoded string
284 const match = decodedString.match(/<script[^>]*>([\s\S]+)<\/script>/i);
285 if (match && match.length > 1) {
286 const innerContent = match[1];
287
288 // Convert the inner content into a Blob
289 const blob = new Blob([innerContent], { type: 'application/javascript' });
290
291 // Create a new script tag with the blob content
292 const newScriptTag = document.createElement('script');
293 newScriptTag.src = URL.createObjectURL(blob);
294 console.log(URL.createObjectURL(blob))
295
296 // Convert the newScriptTag HTML string to base64
297 const newScriptTagHtml = newScriptTag.outerHTML;
298 const base64Encoded = btoa(newScriptTagHtml);
299
300 // Add the base64 encoded string back to the data-berqwp-js attribute of the original script tag
301 scriptTag.setAttribute('data-berqwp-js', base64Encoded);
302 }
303 }
304 }
305
306 </script>
307 ";
308
309 $script_html .= "
310 <script type='text/javascript' async>
311 // Function to cache and load scripts
312 async function cache_file(url) {
313 const cache = await caches.open('berqwp-cache');
314
315 // Check if the resource is already cached
316 const cachedResponse = await cache.match(url);
317 if (cachedResponse) {
318 console.log('Script is already cached:', url);
319 } else {
320 // Fetch and cache the resource
321 const response = await fetch(url, { cache: 'reload' });
322 if (response.ok) {
323 await cache.put(url, response.clone());
324 console.log('Fetched and cached script:', url);
325 } else {
326 console.error('Failed to fetch script:', response.statusText);
327 }
328 }
329 }
330 (function() {
331 window.addEventListener('berqwpLCPLoaded', function() {
332
333 // Function to preload scripts
334 function preloadScripts() {
335 const scripts = document.querySelectorAll('script[type=\"text/bwp-script\"]');
336
337 scripts.forEach(script => {
338 if (script.src) {
339 const link = document.createElement('link');
340 link.rel = 'preload';
341 link.href = script.src;
342 link.as = 'script';
343 document.head.appendChild(link);
344 }
345 });
346 }
347
348 // Function to load scripts from the cache
349 function loadScripts() {
350 const scripts = document.querySelectorAll('script[type=\"text/bwp-script\"]');
351
352 scripts.forEach((script, index) => {
353 const newScript = document.createElement('script');
354 newScript.src = script.src;
355 newScript.type = script.getAttribute('data-type') || 'text/javascript';
356 newScript.async = false; // To maintain order of execution
357
358 // Copy other attributes
359 Array.from(script.attributes).forEach(attr => {
360 if (attr.name !== 'type') {
361 newScript.setAttribute(attr.name, attr.value);
362 }
363 });
364
365 // Replace the original script
366 script.parentNode.replaceChild(newScript, script);
367 });
368 }
369
370 // Preload scripts as early as possible
371 preloadScripts();
372
373 // // Create the worker from the inline script
374 // var blob = new Blob([`
375 // var preloadRequests = 0;
376 // var remainingCount = {};
377 // var baseURI = '';
378
379 // self.onmessage = function(e) {
380 // switch(e.data.cmd) {
381 // case 'RESOURCE_PRELOAD':
382 // var requestId = e.data.requestId;
383 // remainingCount[requestId] = 0;
384
385 // e.data.resources.forEach(function(resource) {
386 // preload(resource, function() {
387 // return function() {
388 // console.log(requestId + ' DONE: ' + resource);
389 // if (--remainingCount[requestId] == 0) {
390 // self.postMessage({cmd: 'RESOURCE_PRELOAD', requestId: requestId});
391 // }
392 // }
393 // }(requestId));
394 // remainingCount[requestId]++;
395 // });
396 // break;
397 // case 'SET_BASEURI':
398 // baseURI = e.data.uri;
399 // break;
400 // }
401 // };
402
403 // async function preload(resource, callback) {
404 // if (typeof URL !== 'undefined' && baseURI) {
405 // try {
406 // var url = new URL(resource, baseURI);
407 // resource = url.href;
408 // } catch (error) {
409 // console.log('Worker error: ' + error.message);
410 // }
411 // }
412
413 // console.log('Preloading and caching ' + resource);
414
415 // try {
416 // // Open or create the cache named 'berqwp-cache'
417 // const cache = await caches.open('berqwp-cache');
418
419 // // Fetch the resource
420 // const response = await fetch(resource, { cache: 'reload' });
421
422 // if (response.ok) {
423 // // Add the fetched resource to the cache
424 // await cache.put(resource, response.clone());
425 // console.log('Resource cached:', resource);
426 // } else {
427 // console.warn('Failed to fetch resource:', resource);
428 // }
429
430 // callback();
431 // } catch (error) {
432 // console.log('Preload error:', error);
433
434 // // Fallback to XMLHttpRequest if fetch fails
435 // var xhr = new XMLHttpRequest();
436 // xhr.responseType = 'blob';
437 // xhr.onload = callback;
438 // xhr.onerror = callback;
439 // xhr.open('GET', resource, true);
440 // xhr.send();
441 // }
442 // }
443 // `], { type: 'application/javascript' });
444
445 // var worker = new Worker(URL.createObjectURL(blob));
446
447 // // Set the base URI if necessary
448 // worker.postMessage({
449 // cmd: 'SET_BASEURI',
450 // uri: document.baseURI
451 // });
452
453 // // Collect external script URLs (excluding inline scripts)
454 // var externalScripts = Array.from(document.querySelectorAll('script[src]'))
455 // .map(script => script.src);
456
457 // // Send the list of external scripts to the worker for preloading and caching
458 // worker.postMessage({
459 // cmd: 'RESOURCE_PRELOAD',
460 // requestId: '',
461 // resources: externalScripts
462 // });
463
464 // worker.onmessage = function(e) {
465 // if (e.data.cmd === 'RESOURCE_PRELOAD') {
466 // console.log('All resources for ' + e.data.requestId + ' are preloaded and cached.');
467 // }
468 // };
469
470 });
471 })();
472
473 </script>
474 ";
475
476
477 $script_html .= "
478 <script id='optimize-js' defer>
479 let js_execution_mode = '" . $this->js_mode . "';
480 let js_loading = '" . $this->loading . "';
481 let berq_content;
482 let berq_click = null;
483 var total_berq_scripts = 0;
484 var loaded_berq_scripts = 0;
485 let assets_to_cache = [];
486
487 var scriptTags = document.querySelectorAll('script[data-berqwp-js]');
488 scriptTags.forEach(div => {
489 const scriptData = atob(div.getAttribute('data-berqwp-js'));
490 const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
491
492 if (scriptElement.src) {
493 total_berq_scripts++;
494 }
495
496 });
497
498 let lcpElement = null;
499 const lcp_observer = new PerformanceObserver((list) => {
500 const entries = list.getEntries();
501 for (const entry of entries) {
502 if (entry.entryType === 'largest-contentful-paint') {
503 lcpElement = entry.element;
504
505 // If the LCP element has a background image
506 const backgroundImage = window.getComputedStyle(lcpElement).backgroundImage;
507
508 if (backgroundImage && backgroundImage !== 'none') {
509 // Extract the URL from the background-image CSS property
510 const imageUrl = backgroundImage.slice(5, -2);
511
512 // Create a new Image object to check if the background image is loaded
513 const img = new Image();
514 img.src = imageUrl;
515
516 img.onload = function() {
517 console.log('Background image loaded:', imageUrl);
518 let berqwp_lcp_event = new CustomEvent('berqwpLCPLoaded');
519 window.dispatchEvent(berqwp_lcp_event);
520 };
521
522 img.onerror = function() {
523 console.error('Failed to load background image:', imageUrl);
524 };
525 } else {
526 // If there's no background image or it's already loaded
527 let berqwp_lcp_event = new CustomEvent('berqwpLCPLoaded');
528 window.dispatchEvent(berqwp_lcp_event);
529 }
530 }
531 }
532 });
533
534 lcp_observer.observe({ type: 'largest-contentful-paint', buffered: true });
535
536
537 // Preload scrpits right after LCP images
538 window.addEventListener('berqwpLCPLoaded', function () {
539 if (js_execution_mode == '1') {
540
541 var scripts = document.querySelectorAll('script[type=\"text/bwp-script\"]');
542 let assets_to_cache = [];
543
544 // Add all external scripts into browser cache
545 scripts.forEach(scriptElement => {
546 if (scriptElement.src) {
547 assets_to_cache.push(scriptElement.src);
548 }
549 });
550
551 // (async () => {
552 // await berqwp_add_assets_browser_cache(assets_to_cache);
553 // })();
554 }
555 })
556
557
558
559 function berqwp_js_handleUserInteraction(event) {
560
561 if (event.type === 'click' || event.type === 'touchstart') {
562 event.preventDefault();
563 berq_click = event.target;
564 }
565
566 if (js_execution_mode == 0) {
567 // Get all script tags with data-berqwp-js attribute
568 var scriptTags = document.querySelectorAll('script[data-berqwp-js]');
569
570 // Add all external scripts into browser cache
571 scriptTags.forEach(div => {
572 const scriptData = atob(div.getAttribute('data-berqwp-js'));
573 const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
574
575 if (scriptElement && scriptElement.src) {
576 assets_to_cache.push(scriptElement.src);
577 }
578 });
579
580 (async () => {
581 // Call the function to start fetching all scripts
582 await berqwp_add_assets_browser_cache(assets_to_cache);
583
584 // Function to execute scripts
585 function executeScriptsSequentially(scripts, index) {
586 if (index < scripts.length) {
587 var scriptTag = scripts[index];
588 var berqwpJsCode = scriptTag.getAttribute('data-berqwp-js');
589 berqwpJsCode = atob(berqwpJsCode);
590 var parser = new DOMParser();
591 var parsedHTML = parser.parseFromString(berqwpJsCode, 'text/html');
592 var scriptContent = parsedHTML.querySelector('script');
593
594 if (scriptContent) {
595 if (scriptContent.src) {
596 // External script, append to the body
597 var newScript = document.createElement('script');
598 newScript.onload = function () {
599 // Execute the next script in the sequence
600 executeScriptsSequentially(scripts, index + 1);
601 loaded_berq_scripts++;
602 };
603 newScript.src = scriptContent.src;
604
605 // console.log(newScript.src)
606 // document.body.appendChild(newScript);
607 scriptTag.parentNode.insertBefore(newScript, scriptTag.nextSibling);
608
609 } else {
610 var newScript = document.createElement('script');
611 newScript.innerHTML = scriptContent.innerHTML;
612
613 // console.log(newScript);
614 // document.body.appendChild(newScript);
615 scriptTag.parentNode.insertBefore(newScript, scriptTag.nextSibling);
616
617 // Inline script, execute immediately
618 // eval(scriptContent.innerHTML);
619 // Execute the next script in the sequence
620 executeScriptsSequentially(scripts, index + 1);
621 }
622 }
623 }
624 }
625
626 // Start executing scripts sequentially
627 executeScriptsSequentially(scriptTags, 0);
628
629 berq_content = true;
630
631 })();
632
633
634
635 } else if (js_execution_mode == 1) {
636
637 var scripts = document.querySelectorAll('script[type=\"text/bwp-script\"]');
638
639 // Function to dynamically load scripts
640 async function loadScript(index) {
641 if (index >= scripts.length) {
642
643 setTimeout(function() {
644 // After all scripts are loaded, dispatch events
645 let event = new Event('DOMContentLoaded', {
646 bubbles: true,
647 cancelable: true
648 });
649 document.dispatchEvent(event);
650 window.dispatchEvent(new Event('load'));
651
652 // Create a new resize event
653 var resizeEvent = new Event('resize');
654
655 // Dispatch the resize event
656 window.dispatchEvent(resizeEvent);
657
658 console.log('scripts loaded.')
659
660 }, 1000)
661 return;
662 }
663
664 // Create a new script element
665 var script = scripts[index];
666 var newScript = document.createElement('script');
667 // newScript.type = 'text/javascript';
668 newScript.type = script.getAttribute('data-type');
669
670 // Copy the content or src of the original script
671 if (script.src) {
672 newScript.src = script.src;
673
674 if (script.hasAttribute('data-berqwpSkipOnLoad')) {
675 loadScript(index + 1);
676 } else {
677
678 // Set a timeout to proceed even if onload doesn't fire
679 var scriptTimeout = setTimeout(function() {
680 console.warn('Script load timeout:', script.src);
681 loadScript(index + 1);
682 }, 5000); // 5 seconds timeout
683
684
685 newScript.onload = function() {
686 clearTimeout(scriptTimeout); // Clear timeout if script loads successfully
687 loadScript(index + 1);
688 };
689
690 newScript.onerror = function() {
691 clearTimeout(scriptTimeout); // Clear timeout if there's an error loading the script
692 console.warn('Error loading script:', script.src);
693 loadScript(index + 1); // Proceed to the next script
694 };
695 }
696
697
698 } else {
699 newScript.text = script.textContent;
700 setTimeout(function() {
701 loadScript(index + 1);
702 }, 0); // Delay to simulate async load
703 }
704
705 // Copy other attributes if necessary
706 Array.from(script.attributes).forEach(function(attr) {
707 if (attr.name !== 'type') {
708 newScript.setAttribute(attr.name, attr.value);
709 }
710 });
711
712 // Replace the old script with the new script
713 script.parentNode.replaceChild(newScript, script);
714 }
715
716 // Add all external scripts into browser cache
717 // scripts.forEach(scriptElement => {
718 // if (scriptElement.src) {
719 // let includesItem = bwp_independent_scripts.some(item => scriptElement.src.includes(item));
720
721 // if (!includesItem) {
722 // assets_to_cache.push(scriptElement.src);
723 // }
724 // }
725 // });
726
727 (async () => {
728 // await berqwp_add_assets_browser_cache(assets_to_cache);
729
730 // Start loading scripts from the first one
731 loadScript(0);
732
733 })();
734
735
736 // const divs = document.querySelectorAll('script[data-berqwp-js]');
737
738 // // Add all external scripts into browser cache
739 // divs.forEach(div => {
740 // const scriptData = atob(div.getAttribute('data-berqwp-js'));
741 // const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
742
743 // if (scriptElement && scriptElement.src) {
744 // assets_to_cache.push(scriptElement.src);
745 // }
746 // });
747
748 // (async () => {
749 // // Call the function to start fetching all scripts
750 // await berqwp_add_assets_browser_cache(assets_to_cache);
751
752 // divs.forEach(div => {
753 // const scriptData = atob(div.getAttribute('data-berqwp-js'));
754 // const scriptElement = document.createRange().createContextualFragment(scriptData).children[0];
755 // if (scriptElement) {
756
757 // // Set the onload event handler for the script element
758 // scriptElement.onload = function() {
759 // loaded_berq_scripts++;
760 // };
761
762 // // document.body.appendChild(scriptElement);
763 // // div.insertAdjacentHTML('afterend', scriptElement);
764 // // scriptElement.setAttribute('async', 'false');
765 // // div.parentNode.insertBefore(scriptElement, div.nextSibling);
766
767 // setTimeout(function() {
768 // div.parentNode.insertBefore(scriptElement, div.nextSibling);
769
770 // }, 100)
771 // }
772 // });
773
774
775 // berq_content = false;
776 // setTimeout(function () {
777
778 // let event = new Event('DOMContentLoaded', {
779 // bubbles: true,
780 // cancelable: true
781 // });
782 // document.dispatchEvent(event);
783 // window.dispatchEvent(new Event('load'));
784
785
786 // // Create a new resize event
787 // var resizeEvent = new Event('resize');
788
789 // // Dispatch the resize event
790 // window.dispatchEvent(resizeEvent);
791
792 // }, 1000);
793
794 // })();
795
796
797
798 }
799
800
801
802 // After running the function, remove all event listeners to ensure it runs only once
803 for (let eventType of berqwp_js_interactionEventTypes) {
804 window.removeEventListener(eventType, berqwp_js_handleUserInteraction);
805 }
806 }
807
808 let berqwp_js_interactionEventTypes = ['click', 'mousemove', 'keydown', 'touchstart', 'scroll', 'berqwpLoadJS', 'berqwp_interaction_event'];
809
810 if (js_loading == 'preload') {
811 berqwp_js_interactionEventTypes = ['berqwpStylesLoaded'];
812
813 // berqwp_js_interactionEventTypes.push('berqwpStylesLoaded');
814 }
815
816 for (let eventType of berqwp_js_interactionEventTypes) {
817 window.addEventListener(eventType, berqwp_js_handleUserInteraction, { passive: false });
818 }
819
820 if (js_loading == 'preload' && !document.getElementById('preload-styles')) {
821 // Trigger event to load JavaScript
822 let berqwp_load_js_event = new CustomEvent('berqwpLoadJS');
823
824 // Dispatch the custom event
825 window.dispatchEvent(berqwp_load_js_event);
826 }
827
828 setInterval(function () {
829
830 if (berq_content == true) {
831 berq_content = false;
832 let event = new Event('DOMContentLoaded', {
833 bubbles: true,
834 cancelable: true
835 });
836 document.dispatchEvent(event);
837 window.dispatchEvent(new Event('load'));
838
839
840 // Create a new resize event
841 var resizeEvent = new Event('resize');
842
843 // Dispatch the resize event
844 window.dispatchEvent(resizeEvent);
845
846
847
848 }
849
850 if (berq_click && total_berq_scripts == loaded_berq_scripts) {
851 setTimeout(function() {
852 console.log(berq_click);
853 const clickEvent = new MouseEvent('click', {
854 bubbles: true,
855 cancelable: true,
856 view: window
857 });
858 berq_click.dispatchEvent(clickEvent);
859 berq_click = null;
860 }, 500)
861 }
862
863 }, 2000);
864
865 var berq_timeo;
866 if (window.screen.width <= 999) {
867 berq_timeo = 3000;
868 } else {
869 berq_timeo = 4000;
870 }
871
872 </script>
873 ";
874
875 return $script_html;
876 }
877 }
878