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