PluginProbe ʕ •ᴥ•ʔ
Core Web Vitals & PageSpeed Booster / 1.0.12
Core Web Vitals & PageSpeed Booster v1.0.12
trunk 1.0 1.0.1 1.0.10 1.0.11 1.0.12 1.0.13 1.0.14 1.0.15 1.0.16 1.0.17 1.0.18 1.0.19 1.0.2 1.0.20 1.0.21 1.0.22 1.0.23 1.0.24 1.0.25 1.0.26 1.0.27 1.0.28 1.0.29 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.7.1 1.0.7.2 1.0.8 1.0.9
core-web-vitals-pagespeed-booster / includes / javascript / delay-js.php
core-web-vitals-pagespeed-booster / includes / javascript Last commit date
delay-js.php 3 years ago delay-jswithjs.php 3 years ago lazyload.js 3 years ago
delay-js.php
850 lines
1 <?php
2 if ( ! defined( 'ABSPATH' ) ) {
3 exit; // Exit if accessed directly.
4 }
5 function cwvpsb_get_atts_array($atts_string) {
6
7 if(!empty($atts_string)) {
8 $atts_array = array_map(
9 function(array $attribute) {
10 return $attribute['value'];
11 },
12 wp_kses_hair($atts_string, wp_allowed_protocols())
13 );
14 return $atts_array;
15 }
16 return false;
17 }
18
19 function cwvpsb_get_atts_string($atts_array) {
20
21 if(!empty($atts_array)) {
22 $assigned_atts_array = array_map(
23 function($name, $value) {
24 if($value === '' || $value === null || $value == "null" ) {
25 return $name;
26 }
27 return sprintf('%s="%s"', $name, esc_attr($value));
28 },
29 array_keys($atts_array),
30 $atts_array
31 );
32 $atts_string = implode(' ', $assigned_atts_array);
33 return $atts_string;
34 }
35 return false;
36 }
37
38 function cwvpsb_delay_js_main() {
39
40 $is_admin = current_user_can('manage_options');
41
42 if(is_admin() || $is_admin){
43 return;
44 }
45
46 if ( function_exists('is_checkout') && is_checkout() || (function_exists('is_feed')&& is_feed()) ) {
47 return;
48 }
49 if( class_exists( 'next_article_layout' ) ) {
50 return ;
51 }
52
53 if ( function_exists('elementor_load_plugin_textdomain') && \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
54 return;
55 }
56 if(cwvpsb_wprocket_lazyjs()){
57 add_filter('rocket_delay_js_exclusions', 'cwvpsb_add_rocket_delay_js_exclusions');
58 return;
59 }
60 add_filter('cwvpsb_complete_html_after_dom_loaded', 'cwvpsb_delay_js_html', 2);
61 add_filter('cwvpsb_complete_html_after_dom_loaded', 'cwvpsb_remove_js_query_param', 99);
62 add_action('wp_footer', 'cwvpsb_delay_js_load', PHP_INT_MAX);
63 }
64 add_action('wp', 'cwvpsb_delay_js_main');
65
66 function cwvpsb_delay_js_html($html) {
67
68 $html_no_comments = $html;//preg_replace('/<!--(.*)-->/Uis', '', $html);
69 preg_match_all('#(<script\s?([^>]+)?\/?>)(.*?)<\/script>#is', $html_no_comments, $matches);
70 if(!isset($matches[0])) {
71 return $html;
72 }
73 $combined_ex_js_arr = array();
74 foreach($matches[0] as $i => $tag) {
75 $atts_array = !empty($matches[2][$i]) ? cwvpsb_get_atts_array($matches[2][$i]) : array();
76 if(isset($atts_array['type']) && stripos($atts_array['type'], 'javascript') == false ||
77 isset($atts_array['id']) && stripos($atts_array['id'], 'corewvps-mergejsfile') !== false ||
78 isset($atts_array['id']) && stripos($atts_array['id'], 'corewvps-cc') !== false
79 ) {
80 continue;
81 }
82 $delay_flag = false;
83 $excluded_scripts = array(
84 'cwvpsb-delayed-scripts',
85 );
86
87 if(!empty($excluded_scripts)) {
88 foreach($excluded_scripts as $excluded_script) {
89 if(strpos($tag, $excluded_script) !== false) {
90 continue 2;
91 }
92 }
93 }
94 // Fix for recaptcha
95 if(strpos($tag,'recaptcha') !== false) {
96 continue 1;
97 }
98 // Fix for google analytics
99 if((strpos($tag,'google-analytics') !== false) || (strpos($tag,'googletagmanager') !== false)) {
100 continue 1;
101 }
102
103 $delay_flag = true;
104 if(!empty($atts_array['type'])) {
105 $atts_array['data-cwvpsb-type'] = $atts_array['type'];
106 }
107
108 $atts_array['type'] = 'cwvpsbdelayedscript';
109 $atts_array['defer'] = 'defer';
110
111 $include = true;
112 if(isset($atts_array['src'])){
113 $regex = cwvpsb_delay_exclude_js();
114
115 if($regex && preg_match( '#(' . $regex . ')#', $atts_array['src'] )){
116 $combined_ex_js_arr[] = $atts_array['src'];
117 //$html = str_replace($tag, '', $html);
118 $include = false;
119 }
120 }
121 if($include && isset($atts_array['id'])){
122 $regex = cwvpsb_delay_exclude_js();
123 $file_path = $atts_array['id'];
124 if($regex && preg_match( '#(' . $regex . ')#', $file_path)){
125 $include = false;
126 }
127 }
128 if($include && isset($matches[3][$i])){
129 $regex = cwvpsb_delay_exclude_js();
130 $file_path = $matches[3][$i];
131 if($regex && preg_match( '#(' . $regex . ')#', $file_path)){
132 $include = false;
133 }
134 }
135 if(isset($atts_array['src']) && !$include){
136 $include = true;
137 }
138 if($delay_flag && $include ) {//
139
140 $delayed_atts_string = cwvpsb_get_atts_string($atts_array);
141 $delayed_tag = sprintf('<script %1$s>', $delayed_atts_string) . (!empty($matches[3][$i]) ? $matches[3][$i] : '') .'</script>';
142 $html = str_replace($tag, $delayed_tag, $html);
143 continue;
144 }
145 }
146 /*if($combined_ex_js_arr){
147 $html = cwvpsb_combine_js_files($combined_ex_js_arr, $html);
148 }*/
149 return $html;
150 }
151
152 // function cwvpsb_combine_js_files($combined_ex_js_arr, $html){
153 // if(!count($combined_ex_js_arr)){ return ; }
154 // include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
155 // include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
156 // if (!class_exists('WP_Filesystem_Direct')) {
157 // return false;
158 // }
159
160 // $uniqueid = get_transient( CWVPSB_CACHE_NAME );
161 // global $wp;
162 // $url = home_url( $wp->request );
163 // $filename = md5($url.$uniqueid);
164
165 // $user_dirname = CWVPSB_JS_EXCLUDE_CACHE_DIR;
166 // $user_urlname = CWVPSB_JS_EXCLUDE_CACHE_URL;
167 // $jsUrl = '';
168
169 // if(!file_exists($user_dirname.'/'.$filename.'.js')){
170
171 // $jscontent = '';
172 // foreach($combined_ex_js_arr as $file_url){
173 // $parse_url = parse_url($file_url);
174 // $file_path = str_replace(array(get_site_url(),'?'.$parse_url['query']),array(ABSPATH,''),$file_url);
175 // $wp_filesystem = new WP_Filesystem_Direct(null);
176 // $js = $wp_filesystem->get_contents($file_path);
177 // unset($wp_filesystem);
178 // if (empty($js)) {
179 // $request = wp_remote_get($file_url);
180 // $js = wp_remote_retrieve_body($request);
181 // }
182 // $jscontent .= "\n/*File: $file_url*/\n".$js;
183 // }
184 // if($jscontent){
185 // $fileSystem = new WP_Filesystem_Direct( new StdClass() );
186 // if(!file_exists($user_dirname)) wp_mkdir_p($user_dirname);
187 // $fileSystem->put_contents($user_dirname.'/'.$filename.'.js', $jscontent, 644 );
188 // unset($fileSystem);
189 // }
190 // }
191 // return $html;
192 // }
193
194 function cwvpsb_remove_js_query_param($html){
195
196
197 $html = preg_replace('/type="cwvpsbdelayedscript"\s+src="(.*?)\.js\?(.*?)"/', 'type="cwvpsbdelayedscript" src="$1.js"', $html);
198 if(preg_match('/<link(.*?)rel="cwvpsbdelayedstyle"(.*?)href="(.*?)\.css\?(.*?)"(.*?)>/m',$html)){
199 $html = preg_replace('/<link(.*?)rel="cwvpsbdelayedstyle"(.*?)href="(.*?)\.css\?(.*?)"(.*?)>/', '<link$1rel="cwvpsbdelayedstyle"$2href="$3.css"$5>', $html);
200 }
201 return $html;
202 }
203
204 function cwvpsb_delay_exclude_js(){
205 $settings = cwvpsb_defaults();
206 $inputs['exclude_js'] = $settings['exclude_delay_js'];
207 if ( ! empty( $inputs['exclude_js'] ) ) {
208 if ( ! is_array( $inputs['exclude_js'] ) ) {
209 $inputs['exclude_js'] = explode( "\n", $inputs['exclude_js'] );
210 }
211 $inputs['exclude_js'] = array_map( 'trim', $inputs['exclude_js'] );
212 //$inputs['exclude_js'] = array_map( 'cwvpsb_sanitize_js', $inputs['exclude_js'] );
213 $inputs['exclude_js'] = (array) array_filter( $inputs['exclude_js'] );
214 $inputs['exclude_js'] = array_unique( $inputs['exclude_js'] );
215 } else {
216 $inputs['exclude_js'] = array();
217 }
218 $excluded_files = array();
219 if($inputs['exclude_js']){
220 foreach ( $inputs['exclude_js'] as $i => $excluded_file ) {
221 // Escape characters for future use in regex pattern.
222 $excluded_files[ $i ] = str_replace( '#', '\#', $excluded_file );
223 }
224 }
225 if(is_array($excluded_files)){
226 return implode( '|', $excluded_files );
227 }else{
228 return '';
229 }
230 }
231 add_action( 'wp_enqueue_scripts', 'cwvpsb_scripts_styles' , 99999);
232 function cwvpsb_scripts_styles(){
233
234 global $wp_scripts;
235 $wp_scripts->all_deps($wp_scripts->queue);
236
237 $uniqueid = get_transient( CWVPSB_CACHE_NAME );
238 global $wp;
239 $url = home_url( $wp->request );
240 $filename = md5($url.$uniqueid);
241 $user_dirname = CWVPSB_JS_EXCLUDE_CACHE_DIR;
242 $user_urlname = CWVPSB_JS_EXCLUDE_CACHE_URL;
243
244
245 if(!file_exists($user_dirname.'/'.$filename.'.js')){
246 $combined_ex_js_arr= array();
247 $jscontent = '';
248 $regex = cwvpsb_delay_exclude_js();
249 include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
250 include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
251 if (!class_exists('WP_Filesystem_Direct')) {
252 return false;
253 }
254 $wp_scripts->all_deps($wp_scripts->queue);
255 foreach( $wp_scripts->to_do as $key=>$handle)
256 {
257 $localize = $localize_handle = '';
258 //$src = strtok($wp_scripts->registered[$handle]->src, '?');
259 if($regex && preg_match( '#(' . $regex . ')#', $wp_scripts->registered[$handle]->src )){
260 $localize_handle = $handle;
261 }
262 if($regex && preg_match( '#(' . $regex . ')#', $handle )){
263 $localize_handle = $handle;
264 }
265 if($localize_handle){
266 if(@array_key_exists('data', $wp_scripts->registered[$handle]->extra)) {
267 $localize = $wp_scripts->registered[$handle]->extra['data'] . ';';
268 }
269 $file_url = $wp_scripts->registered[$handle]->src;
270 $parse_url = parse_url($file_url);
271 $file_path = str_replace(array(get_site_url(),'?'.@$parse_url['query']),array(ABSPATH,''),$file_url);
272
273 if(substr( $file_path, 0, 13 ) === "/wp-includes/"){
274 $file_path = ABSPATH.$file_path;
275 }
276 $wp_filesystem = new WP_Filesystem_Direct(null);
277 $js = $wp_filesystem->get_contents($file_path);
278 unset($wp_filesystem);
279 if (empty($js)) {
280 $request = wp_remote_get($file_url);
281 $js = wp_remote_retrieve_body($request);
282 }
283
284
285 //$combined_ex_js_arr[$handle] = ;
286 $jscontent .= "\n/*File: $file_url*/\n".$localize.$js;
287
288 //wp_deregister_script($handle);
289 }
290 }
291 if($jscontent){
292 $fileSystem = new WP_Filesystem_Direct( new StdClass() );
293 if(!file_exists($user_dirname)) wp_mkdir_p($user_dirname);
294 $fileSystem->put_contents($user_dirname.'/'.$filename.'.js', $jscontent, 644 );
295 unset($fileSystem);
296 }
297 }
298
299
300 $uniqueid = get_transient( CWVPSB_CACHE_NAME );
301 global $wp;
302 $url = home_url( $wp->request );
303 $filename = md5($url.$uniqueid);
304 $user_dirname = CWVPSB_JS_EXCLUDE_CACHE_DIR;
305 $user_urlname = CWVPSB_JS_EXCLUDE_CACHE_URL;
306
307 if(file_exists($user_dirname.'/'.$filename.'.js')){
308 wp_register_script('corewvps-mergejsfile', $user_urlname.'/'.$filename.'.js', array(), CWVPSB_VERSION, true);
309 wp_enqueue_script('corewvps-mergejsfile');
310 }
311
312 }
313 add_filter( 'script_loader_src', 'cwvpsb_remove_css_js_version', 9999, 2 );
314 function cwvpsb_remove_css_js_version($src, $handle ){
315 $handles_with_version = [ 'corewvps-mergejsfile', 'corewvps-cc','corewvps-mergecssfile' ];
316 if ( strpos( $src, 'ver=' ) && in_array( $handle, $handles_with_version, true ) ){
317 //$src = remove_query_arg( 'ver', $src );
318 }
319 $src = add_query_arg( 'time', time(), $src );
320 return $src;
321 }
322
323
324 function cwvpsb_merge_js_scripts(){
325 global $wp_scripts;
326 $wp_scripts->all_deps($wp_scripts->queue);
327
328 $uniqueid = get_transient( CWVPSB_CACHE_NAME );
329 global $wp;
330 $url = home_url( $wp->request );
331 $filename = md5($url.$uniqueid);
332 $user_dirname = CWVPSB_JS_MERGE_FILE_CACHE_DIR;
333 $user_urlname = CWVPSB_JS_MERGE_FILE_CACHE_CACHE_URL;
334
335 if(!file_exists($user_dirname.'/'.$filename.'.js')){
336 $combined_ex_js_arr= array();
337 $jscontent = '';
338 $regex = cwvpsb_delay_exclude_js();
339 include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
340 include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
341 if (!class_exists('WP_Filesystem_Direct')) {
342 return false;
343 }
344 $wp_scripts->all_deps($wp_scripts->queue);
345 foreach( $wp_scripts->to_do as $key=>$handle)
346 {
347 $localize = '';
348 $localize_handle = 'cwvpsb-merged-js';
349 //$src = strtok($wp_scripts->registered[$handle]->src, '?');
350 if($regex && preg_match( '#(' . $regex . ')#', $wp_scripts->registered[$handle]->src )){
351 $localize_handle = $handle;
352 }
353 if($regex && preg_match( '#(' . $regex . ')#', $handle )){
354 $localize_handle = $handle;
355 }
356
357
358 if($localize_handle == 'cwvpsb-merged-js'){
359 if(@array_key_exists('data', $wp_scripts->registered[$handle]->extra)) {
360 $localize = $wp_scripts->registered[$handle]->extra['data'] . ';';
361 }
362 $file_url = $wp_scripts->registered[$handle]->src;
363 $parse_url = parse_url($file_url);
364 $file_path = str_replace(array(get_site_url(),'?'.@$parse_url['query']),array(ABSPATH,''),$file_url);
365
366 if(substr( $file_path, 0, 13 ) === "/wp-includes/"){
367 $file_path = ABSPATH.$file_path;
368 }
369 $wp_filesystem = new WP_Filesystem_Direct(null);
370 if(file_exists($file_path)){
371 $js = $wp_filesystem->get_contents($file_path);
372 }
373 unset($wp_filesystem);
374 if (empty($js)) {
375 $request = wp_remote_get($file_url);
376 $js = wp_remote_retrieve_body($request);
377 }
378
379
380 //$combined_ex_js_arr[$handle] = ;
381 $jscontent .= "\n/*File: $file_url*/\n".$localize.$js;
382
383 //wp_deregister_script($handle);
384 }
385 }
386 if($jscontent){
387 $fileSystem = new WP_Filesystem_Direct( new StdClass() );
388 if(!file_exists($user_dirname)) wp_mkdir_p($user_dirname);
389 $fileSystem->put_contents($user_dirname.'/'.$filename.'.js', $jscontent, 644 );
390 unset($fileSystem);
391 }
392 }
393
394
395 $uniqueid = get_transient( CWVPSB_CACHE_NAME );
396 global $wp;
397 $url = home_url( $wp->request );
398 $filename = md5($url.$uniqueid);
399 $user_dirname = CWVPSB_JS_MERGE_FILE_CACHE_DIR;
400 $user_urlname = CWVPSB_JS_MERGE_FILE_CACHE_CACHE_URL;
401
402 if(file_exists($user_dirname.'/'.$filename.'.js')){
403 wp_register_script('corewvps-delayjs-mergedfile', $user_urlname.'/'.$filename.'.js', array(), CWVPSB_VERSION, true);
404 wp_enqueue_script('corewvps-delayjs-mergedfile');
405 }
406
407 }
408
409 // Merged CSS Code Starts here....
410
411 //add_action( 'wp_enqueue_scripts', 'cwvpsb_merge_css_scripts_styles' , 99999);
412 function cwvpsb_merge_css_scripts_styles(){
413 global $wp_styles;
414 $wp_styles->all_deps($wp_styles->queue);
415
416 $uniqueid = get_transient( CWVPSB_CACHE_NAME );
417 global $wp;
418 $url = home_url( $wp->request );
419 $filename = md5($url.$uniqueid);
420 $user_dirname = CWVPSB_CSS_MERGE_FILE_CACHE_DIR;
421 $user_urlname = CWVPSB_CSS_MERGE_FILE_CACHE_CACHE_URL;
422
423
424 if(!file_exists($user_dirname.'/'.$filename.'.css')){
425 $combined_ex_js_arr= array();
426 $csscontent = '';
427
428 include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
429 include_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
430 if (!class_exists('WP_Filesystem_Direct')) {
431 return false;
432 }
433
434 $wp_styles->all_deps($wp_styles->queue);
435
436
437
438 foreach( $wp_styles->to_do as $key=>$handle)
439 {
440 $localize = '';
441
442
443 if(@array_key_exists('data', $wp_styles->registered[$handle]->extra)) {
444 $localize = $wp_styles->registered[$handle]->extra['data'] . ';';
445 }
446
447
448 $file_url = $wp_styles->registered[$handle]->src;
449
450 $parse_url = parse_url($file_url);
451 $file_path = str_replace(array(get_site_url(),'?'.@$parse_url['query']),array(ABSPATH,''),$file_url);
452
453 if(substr( $file_path, 0, 13 ) === "/wp-includes/"){
454 $file_path = ABSPATH.$file_path;
455 }
456
457 $wp_filesystem = new WP_Filesystem_Direct(null);
458 if(file_exists($file_path)){
459 $css = $wp_filesystem->get_contents($file_path);
460 }
461
462 if (empty($css)) {
463 $request = wp_remote_get($file_url);
464 $css = wp_remote_retrieve_body($request);
465 }
466
467 if(preg_match('/url\([^"|^\'](.*?)\/fonts\/(.*?)\)/m',$css)){
468 $css = preg_replace('/url\([^"|^\'](.*?)\/fonts\/(.*?)\)/m','url(".$1/fonts/$2")',$css);
469 }
470
471
472 if(preg_match_all('/url\((\'|\")[^data](.*?)\/fonts\//m',$css,$matches,PREG_SET_ORDER)){
473
474 $slash_count = count(explode('/',$matches[0][2])) + 1;
475 $explode_fileurl = explode('/',$file_url);
476
477 $file_url_count = count($explode_fileurl);
478
479 $initial_point = $file_url_count - $slash_count;
480
481 $exclude_url = '';
482 for($i = $initial_point;$i < $file_url_count;$i++ ){
483 $exclude_url .= '/'.$explode_fileurl[$i];
484
485 }
486 $font_url = str_replace($exclude_url,'', $file_url);
487 $css = preg_replace('/url\((\'|\")[^data](.*?)\/fonts\//m','url($1'.$font_url.'/fonts/',$css);
488
489 }
490
491
492 if(preg_match('/url\([^"|^\'](.*?)(woff|ttf|eot)(.*?)\)/m',$css)){
493
494 $css = preg_replace('/url\([^"|^\'](.*?)(woff|ttf|eot)(.*?)\)/m','url("$1$2$3")',$css);
495 }
496
497 if(!preg_match('/url\((\'|\")[^data](.*?)\/fonts\//m',$css)){
498
499 $explode_url = explode('/',$file_url);
500
501 $file_ex_index = count($explode_url)-1;
502
503 $new_font_url = str_replace($explode_url[$file_ex_index],'',$file_url);
504
505
506 if(preg_match('/url\((\'|\")fonts(.*?)(woff|ttf|eot)/m',$css)){
507 $css = preg_replace('/url\((\'|\")fonts(.*?)(woff|ttf|eot)/m','url($1'.$new_font_url.'fonts$2$3',$css);
508
509 }elseif(preg_match('/url\((\'|\")(.*?)(woff|ttf|eot)/m',$css)){
510 $css = preg_replace('/url\((\'|\")(.*?)(woff|ttf|eot)/m','url($1'.$new_font_url.'$2$3',$css);
511 }
512 }
513
514 $css = preg_replace(
515 array(
516 // Remove comment(s)
517 '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
518 // Remove unused white-space(s)
519 '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
520 // Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
521 '#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
522 // Replace `:0 0 0 0` with `:0`
523 '#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
524 // Replace `background-position:0` with `background-position:0 0`
525 '#(background-position):0(?=[;\}])#si',
526 // Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
527 '#(?<=[\s:,\-])0+\.(\d+)#s',
528 // Minify string value
529 '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
530 '#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
531 // Minify HEX color code
532 '#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
533 // Replace `(border|outline):none` with `(border|outline):0`
534 '#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
535 // Remove empty selector(s)
536 '#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s'
537 ),
538 array(
539 '$1',
540 '$1$2$3$4$5$6$7',
541 '$1',
542 ':0',
543 '$1:0 0',
544 '.$1',
545 '$1$3',
546 '$1$2$4$5',
547 '$1$2$3',
548 '$1:0',
549 '$1$2'
550 ),
551 $css);
552 //$combined_ex_js_arr[$handle] = ;
553 $csscontent .= "\n/*File: $file_url*/\n".$localize.$css;
554
555 //wp_deregister_script($handle);
556 }
557 if($csscontent){
558 $fileSystem = new WP_Filesystem_Direct( new StdClass() );
559 if(!file_exists($user_dirname)) wp_mkdir_p($user_dirname);
560 $fileSystem->put_contents($user_dirname.'/'.$filename.'.css', $csscontent, 644 );
561 unset($fileSystem);
562 }
563 }
564
565
566 $uniqueid = get_transient( CWVPSB_CACHE_NAME );
567 global $wp;
568 $url = home_url( $wp->request );
569 $filename = md5($url.$uniqueid);
570 $user_dirname = CWVPSB_CSS_MERGE_FILE_CACHE_DIR;
571 $user_urlname = CWVPSB_CSS_MERGE_FILE_CACHE_CACHE_URL;
572
573 if(file_exists($user_dirname.'/'.$filename.'.css')){
574 foreach( $wp_styles->to_do as $key=>$handle) {
575 $wp_styles->add_data( $handle, 'title', 'cwvpsbenqueuedstyles' );
576 }
577 wp_register_style('corewvps-mergecssfile', $user_urlname.'/'.$filename.'.css', array(), '1.0.25', true);
578 wp_enqueue_style('corewvps-mergecssfile');
579 }
580
581 }
582
583 // Merged CSS Code End here....
584
585 function cwvpsb_sanitize_js( $file ) {
586 $file = preg_replace( '#\?.*$#', '', $file );
587 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
588 return ( 'js' === $ext ) ? trim( $file ) : false;
589 }
590
591 add_action('wp_ajax_cwvpsb_delay_ajax_request','cwvpsb_delay_ajax_request');
592 add_action('wp_ajax_nopriv_cwvpsb_delay_ajax_request','cwvpsb_delay_ajax_request');
593 function cwvpsb_delay_ajax_request(){
594 echo 'success';
595 exit();
596 }
597
598 function cwvpsb_delay_js_load() {
599 $js_content = '<script type="text/javascript" id="cwvpsb-delayed-scripts">
600 cwvpsbUserInteractions=["keydown","mousemove","wheel","touchmove","touchstart","touchend","touchcancel","touchforcechange"],cwvpsbDelayedScripts={normal:[],defer:[],async:[],jquery:[]},jQueriesArray=[];var cwvpsbDOMLoaded=!1;
601 function cwvpsbTriggerDOMListener(){cwvpsbUserInteractions.forEach(function(e){window.removeEventListener(e,cwvpsbTriggerDOMListener,{passive:!0})}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",cwvpsbTriggerDelayedScripts):cwvpsbTriggerDelayedScripts()}
602
603 var time = Date.now;
604 var ccfw_loaded = false;
605 function calculate_load_times() {
606 // Check performance support
607 if (performance === undefined) {
608 console.log("= Calculate Load Times: performance NOT supported");
609 return;
610 }
611
612 // Get a list of "resource" performance entries
613 var resources_length=0;
614 var resources = performance.getEntriesByType("resource");
615 if (resources === undefined || resources.length <= 0) {
616 console.log("= Calculate Load Times: there are NO `resource` performance records");
617 }
618 if(resources.length)
619 {
620 resources_length=resources.length;
621 }
622
623 let is_last_resource = 0;
624 for (var i=0; i < resources.length; i++) {
625 if(resources[i].responseEnd>0){
626 is_last_resource = is_last_resource + 1;
627 }
628 }
629
630 let uag = navigator.userAgent;
631 let gpat = /Google Page Speed Insights/gm;
632 let gres = uag.match(gpat);
633 let cpat = /Chrome-Lighthouse/gm;
634 let cres = uag.match(cpat);
635 let wait_till=1000;
636 if(gres || cres){
637 wait_till = 3000;
638 }
639 if(is_last_resource==resources.length){
640 setTimeout(function(){
641 cwvpsbTriggerDelayedScripts();
642 },wait_till);
643 }
644 }
645
646 window.addEventListener("load", function(e) {
647 console.log("load complete");
648 setTimeout(function(){
649 calculate_load_times();
650 },200);
651 });
652
653 async function cwvpsbTriggerDelayedScripts() {
654 if(ccfw_loaded){ return ;}
655 ctl(), cwvpsbDelayEventListeners(), cwvpsbDelayJQueryReady(), cwvpsbProcessDocumentWrite(), cwvpsbSortDelayedScripts(), cwvpsbPreloadDelayedScripts(),await cwvpsbLoadDelayedScripts(cwvpsbDelayedScripts.jquery), await cwvpsbLoadDelayedScripts(cwvpsbDelayedScripts.normal), await cwvpsbLoadDelayedScripts(cwvpsbDelayedScripts.defer), await cwvpsbLoadDelayedScripts(cwvpsbDelayedScripts.async), await cwvpsbTriggerEventListeners()
656 }
657
658 function cwvpsbDelayEventListeners() {
659 let e = {};
660
661 function t(t, n) {
662 function r(n) {
663 return e[t].delayedEvents.indexOf(n) >= 0 ? "cwvpsb-" + n : n
664 }
665 e[t] || (e[t] = {
666 originalFunctions: {
667 add: t.addEventListener,
668 remove: t.removeEventListener
669 },
670 delayedEvents: []
671 }, t.addEventListener = function() {
672 arguments[0] = r(arguments[0]), e[t].originalFunctions.add.apply(t, arguments)
673 }, t.removeEventListener = function() {
674 arguments[0] = r(arguments[0]), e[t].originalFunctions.remove.apply(t, arguments)
675 }), e[t].delayedEvents.push(n)
676 }
677
678 function n(e, t) {
679 const n = e[t];
680 Object.defineProperty(e, t, {
681 get: n || function() {},
682 set: function(n) {
683 e["cwvpsb" + t] = n
684 }
685 })
686 }
687 t(document, "DOMContentLoaded"), t(window, "DOMContentLoaded"), t(window, "load"), t(window, "pageshow"), t(document, "readystatechange"), n(document, "onreadystatechange"), n(window, "onload"), n(window, "onpageshow")
688 }
689
690 function cwvpsbDelayJQueryReady() {
691 let e = window.jQuery;
692 Object.defineProperty(window, "jQuery", {
693 get: () => e,
694 set(t) {
695 if (t && t.fn && !jQueriesArray.includes(t)) {
696 t.fn.ready = t.fn.init.prototype.ready = function(e) {
697 cwvpsbDOMLoaded ? e.bind(document)(t) : document.addEventListener("cwvpsb-DOMContentLoaded", function() {
698 e.bind(document)(t)
699 })
700 };
701 const e = t.fn.on;
702 t.fn.on = t.fn.init.prototype.on = function() {
703 if (this[0] === window) {
704 function t(e) {
705 return e.split(" ").map(e => "load" === e || 0 === e.indexOf("load.") ? "cwvpsb-jquery-load" : e).join(" ")
706 }
707 "string" == typeof arguments[0] || arguments[0] instanceof String ? arguments[0] = t(arguments[0]) : "object" == typeof arguments[0] && Object.keys(arguments[0]).forEach(function(e) {
708 delete Object.assign(arguments[0], {
709 [t(e)]: arguments[0][e]
710 })[e]
711 })
712 }
713 return e.apply(this, arguments), this
714 }, jQueriesArray.push(t)
715 }
716 e = t
717 }
718 })
719 }
720
721 function cwvpsbProcessDocumentWrite() {
722 const e = new Map;
723 document.write = document.writeln = function(t) {
724 var n = document.currentScript,
725 r = document.createRange();
726 let a = e.get(n);
727 void 0 === a && (a = n.nextSibling, e.set(n, a));
728 var o = document.createDocumentFragment();
729 r.setStart(o, 0), o.appendChild(r.createContextualFragment(t)), n.parentElement.insertBefore(o, a)
730 }
731 }
732
733 function cwvpsbSortDelayedScripts() {
734 document.querySelectorAll("script[type=cwvpsbdelayedscript]").forEach(function(e) {
735 e.hasAttribute("src")&&(e.getAttribute("src").match("jquery.min.js")||e.getAttribute("src").match("jquery-migrate.min.js"))?cwvpsbDelayedScripts.jquery.push(e):e.hasAttribute("src")?e.hasAttribute("defer")&&!1!==e.defer?cwvpsbDelayedScripts.defer.push(e):e.hasAttribute("async")&&!1!==e.async?cwvpsbDelayedScripts.async.push(e):cwvpsbDelayedScripts.normal.push(e):cwvpsbDelayedScripts.normal.push(e);
736 })
737 }
738
739 function cwvpsbPreloadDelayedScripts() {
740 var e = document.createDocumentFragment();
741 [...cwvpsbDelayedScripts.normal, ...cwvpsbDelayedScripts.defer, ...cwvpsbDelayedScripts.async].forEach(function(t) {
742 var n = removeVersionFromLink(t.getAttribute("src"));
743 if (n) {
744 t.setAttribute("src", n);
745 var r = document.createElement("link");
746 r.href = n, r.rel = "preload", r.as = "script", e.appendChild(r)
747 }
748 }), document.head.appendChild(e)
749 }
750 async function cwvpsbLoadDelayedScripts(e) {
751 var t = e.shift();
752 return t ? (await cwvpsbReplaceScript(t), cwvpsbLoadDelayedScripts(e)) : Promise.resolve()
753 }
754 async function cwvpsbReplaceScript(e) {
755 return await cwvpsbNextFrame(), new Promise(function(t) {
756 const n = document.createElement("script");
757 [...e.attributes].forEach(function(e) {
758 let t = e.nodeName;
759 "type" !== t && ("data-type" === t && (t = "type"), n.setAttribute(t, e.nodeValue))
760 }), e.hasAttribute("src") ? (n.addEventListener("load", t), n.addEventListener("error", t)) : (n.text = e.text, t()), e.parentNode.replaceChild(n, e)
761 })
762 }
763
764 function ctl(){
765 var cssEle = document.querySelectorAll("link[rel=cwvpsbdelayedstyle]");
766 for(var i=0; i <= cssEle.length;i++){
767 if(cssEle[i]){
768 cssEle[i].href = removeVersionFromLink(cssEle[i].href);
769 cssEle[i].rel = "stylesheet";
770 cssEle[i].type = "text/css";
771 }
772 }
773
774
775 var cssEle = document.querySelectorAll("style[type=cwvpsbdelayedstyle]");
776 for(var i=0; i <= cssEle.length;i++){
777 if(cssEle[i]){
778 cssEle[i].type = "text/css";
779 }
780 }
781 ccfw_loaded=true;
782 }
783 function removeVersionFromLink(link)
784 {
785 if(cwvpbIsValidUrl(link))
786 {
787 const url = new URL(cwvpbFormatLink(link));
788 url.searchParams.delete("ver");
789 url.searchParams.delete("time");
790 return url.href;
791 }
792 return link;
793 }
794
795 function cwvpbIsValidUrl(urlString)
796 {
797 if(urlString){
798 var expression =/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
799 var regex = new RegExp(expression);
800 return urlString.match(regex);
801 }
802 return false;
803 }
804 function cwvpbFormatLink(link)
805 {
806 let http_check=link.match("http:");
807 let https_check=link.match("https:");
808 if(!http_check && !https_check)
809 {
810 return location.protocol+link;
811 }
812 return link;
813 }
814
815 async function cwvpsbTriggerEventListeners() {
816 cwvpsbDOMLoaded = !0, await cwvpsbNextFrame(), document.dispatchEvent(new Event("cwvpsb-DOMContentLoaded")), await cwvpsbNextFrame(), window.dispatchEvent(new Event("cwvpsb-DOMContentLoaded")), await cwvpsbNextFrame(), document.dispatchEvent(new Event("cwvpsb-readystatechange")), await cwvpsbNextFrame(), document.cwvpsbonreadystatechange && document.cwvpsbonreadystatechange(), await cwvpsbNextFrame(), window.dispatchEvent(new Event("cwvpsb-load")), await cwvpsbNextFrame(), window.cwvpsbonload && window.cwvpsbonload(), await cwvpsbNextFrame(), jQueriesArray.forEach(function(e) {
817 e(window).trigger("cwvpsb-jquery-load")
818 }), window.dispatchEvent(new Event("cwvpsb-pageshow")), await cwvpsbNextFrame(), window.cwvpsbonpageshow && window.cwvpsbonpageshow()
819 }
820 async function cwvpsbNextFrame() {
821 return new Promise(function(e) {
822 requestAnimationFrame(e)
823 })
824 }
825 cwvpsbUserInteractions.forEach(function(e) {
826 window.addEventListener(e, cwvpsbTriggerDOMListener, {
827 passive: !0
828 })
829 });</script>';
830 echo $js_content;
831 }
832
833 function cwvpsb_wprocket_lazyjs()
834 {
835 if(defined('WP_ROCKET_VERSION'))
836 {
837 $cwvpsb_wprocket_options=get_option('wp_rocket_settings',null);
838
839 if(isset($cwvpsb_wprocket_options['defer_all_js']) && $cwvpsb_wprocket_options['defer_all_js']==1)
840 {
841 return true;
842 }
843 }
844 return false;
845 }
846
847 function cwvpsb_add_rocket_delay_js_exclusions( $patterns ) {
848 $patterns[] = 'cwvpsb-delayed-scripts';
849 return $patterns;
850 }