PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 3.2.21
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v3.2.21
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / js / minify.js

minify.js in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 3.2.21, at js/minify.js

641 lines 18.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function ($) {
2 var wp_optimize = window.wp_optimize || {};
3 var send_command = wp_optimize.send_command;
4 var refresh_frequency = wpoptimize.refresh_frequency || 30000;
5
6 if (!send_command) {
7 console.error('WP-Optimize Minify: wp_optimize.send_command is required.');
8 return;
9 }
10
11 var minify = {};
12
13 /**
14 * Initializing the minify feature and events
15 */
16 minify.init = function () {
17
18 var minify = this;
19 this.enabled = false;
20
21 $(document).on('wp-optimize/minify/toggle-status', function(e, params) {
22 if (params.hasOwnProperty('enabled')) {
23 $('[data-whichpage="wpo_minify"]').toggleClass('is-enabled', params.enabled)
24 minify.enabled = params.enabled;
25 if (minify.enabled) minify.getFiles();
26 }
27 });
28
29 /**
30 * The standard handler for clearing the cache. Safe to use
31 */
32 $('.purge_minify_cache').on('click', function(e) {
33 e.preventDefault();
34 $.blockUI();
35 send_command('purge_minify_cache', null, function(response) {
36 if (response.hasOwnProperty('files')) {
37 minify.updateFilesLists(response.files);
38 minify.updateStats(response.files);
39 }
40 }).always(function() {
41 $.unblockUI();
42 });
43 });
44
45 /**
46 * Removes the entire cache dir.
47 * Use with caution, as cached html may still reference those files.
48 */
49 $('.purge_all_minify_cache').on('click', function() {
50 $.blockUI();
51 send_command('purge_all_minify_cache', null, function(response) {
52 if (response.hasOwnProperty('files')) {
53 minify.updateFilesLists(response.files);
54 minify.updateStats(response.files);
55 }
56 }).always(function() {
57 $.unblockUI();
58 });
59 });
60
61 /**
62 * Forces minifiy to create a new cache, safe to use
63 */
64 $('.minify_increment_cache').on('click', function() {
65 $.blockUI();
66 send_command('minify_increment_cache', null, function(response) {
67 if (response.hasOwnProperty('files')) {
68 minify.updateFilesLists(response.files);
69 minify.updateStats(response.files);
70 }
71 }).always(function() {
72 $.unblockUI();
73 });
74 });
75
76
77 // ======= SLIDERS ========
78 // Generic slider save
79 $('#wp-optimize-nav-tab-wpo_minify-status-contents form :input, #wp-optimize-nav-tab-wpo_minify-js-contents form :input, #wp-optimize-nav-tab-wpo_minify-css-contents form :input, #wp-optimize-nav-tab-wpo_minify-font-contents form :input, #wp-optimize-nav-tab-wpo_minify-settings-contents form :input, #wp-optimize-nav-tab-wpo_minify-advanced-contents form :input').on('change', function() {
80 $(this).closest('form').data('need_saving', true);
81 });
82
83 $('input[type=checkbox].wpo-save-setting').on('change', function(e) {
84 var input = $(this),
85 val = input.prop('checked'),
86 name = input.prop('name'),
87 data = {};
88 data[name] = val;
89 $.blockUI();
90 send_command('save_minify_settings', data, function(response) {
91 if (response.success) {
92 input.trigger('wp-optimize/minify/saved_setting');
93 if (response.hasOwnProperty('files')) {
94 minify.updateFilesLists(response.files);
95 minify.updateStats(response.files);
96 }
97 } else {
98 console.log('Settings not saved', data)
99 }
100 }).always(function() {
101 $.unblockUI();
102 });
103 });
104
105 // Slider enable minify
106 $('#wpo_min_enable_minify').on('wp-optimize/minify/saved_setting', function() {
107 this.enabled = $(this).prop('checked');
108 $(document).trigger('wp-optimize/minify/toggle-status', {enabled: this.enabled});
109 });
110
111 // Toggle wpo-feature-is-disabled class
112 $('#wpo_min_enable_minify').on('wp-optimize/minify/saved_setting', function() {
113
114 $(this).closest('.wpo_section').toggleClass('wpo-feature-is-disabled', !$(this).is(':checked'));
115 });
116
117 // Toggle wpo-feature-is-disabled class
118 $('#wpo_min_enable_minify_css, #wpo_min_enable_minify_js')
119 // Set value on status change
120 .on('wp-optimize/minify/saved_setting', function() {
121 $('#wp-optimize-nav-tab-wrapper__wpo_minify a[data-tab="' + $(this).data('tabname') + '"] span.disabled').toggleClass('hidden', $(this).is(':checked'));
122 })
123 // Set value on page load
124 .each(function() {
125 $('#wp-optimize-nav-tab-wrapper__wpo_minify a[data-tab="' + $(this).data('tabname') + '"] span.disabled').toggleClass('hidden', $(this).is(':checked'));
126 });
127
128 // slider enable Debug mode
129 $('#wpo_min_enable_minify_debug').on('wp-optimize/minify/saved_setting', function() {
130 // Refresh the page as it's needed to show the extra options
131 $.blockUI({message: '<h1>'+wpoptimize.page_refresh+'</h1>'});
132 location.href = $('#wp-optimize-nav-tab-wpo_minify-advanced').prop('href');
133 });
134
135 // Edit default exclusions
136 $('#wpo_min_edit_default_exclutions').on('wp-optimize/minify/saved_setting', function() {
137 // Show exclusions section
138 $('.wpo-minify-default-exclusions').toggleClass('hidden', !$(this).prop('checked'));
139 });
140
141 // Save settings
142 $('.wp-optimize-save-minify-settings').on('click', function(e) {
143 e.preventDefault();
144 var btn = $(this),
145 spinner = btn.next(),
146 success_icon = spinner.next(),
147 $need_refresh_btn = null;
148
149 spinner.show();
150 $.blockUI();
151
152 var data = {};
153
154 var tabs = $('[data-whichpage="wpo_minify"] .wp-optimize-nav-tab-contents form');
155 tabs.each(function() {
156 var tab = $(this);
157 if (true === tab.data('need_saving')) {
158 data = Object.assign(data, gather_data(tab));
159 tab.data('need_saving', false);
160 }
161 });
162
163 send_command('save_minify_settings', data, function(response) {
164 if (response.hasOwnProperty('error')) {
165 // show error
166 console.log(response.error);
167 wp_optimize.notices.show_notice(response.success, response.error);
168 } else {
169 $('.wpo-error__enabling-cache').addClass('wpo_hidden').find('p').text('');
170 }
171
172 if (response.hasOwnProperty('files')) {
173 minify.updateFilesLists(response.files);
174 minify.updateStats(response.files);
175 }
176
177 spinner.hide();
178 success_icon.show();
179 setTimeout(function() {
180 success_icon.fadeOut('slow', function() {
181 success_icon.hide();
182 });
183 }, 5000);
184 }).always(function() {
185 $.unblockUI();
186 });
187 })
188
189 // Dismiss information notice
190 $('.wp-optimize-minify-status-information-notice').on('click', '.notice-dismiss', function(e) {
191 e.preventDefault();
192 send_command('hide_minify_notice');
193 });
194
195 // Show logs
196 $('#wpo_min_jsprocessed, #wpo_min_cssprocessed').on('click', '.log', function(e) {
197 e.preventDefault();
198 $(this).nextAll('.wpo_min_log').slideToggle('fast');
199 });
200
201 // Delete log file
202 $('#wpo_min_jsprocessed, #wpo_min_cssprocessed').on('click', '.delete-file', function(e) {
203 e.preventDefault();
204
205 var filename = $(this).data('filename');
206
207 if ('' === filename || undefined === filename) {
208 alert(wpoptimize.cache_file_not_found);
209 return false;
210 }
211
212 $.blockUI();
213 send_command('delete_minify_cache_file', filename, function(response) {
214 if('' !== response.files) {
215 minify.updateFilesLists(response.files);
216 minify.updateStats(response.files);
217 }
218 if('' !== response.result) {
219 alert(response.result);
220 }
221 if('' !== response.error) {
222 alert(response.error);
223 }
224 }).always(function() {
225 $.unblockUI();
226 });
227 });
228
229 // Handle js excludes
230 $('#wpo_min_jsprocessed').on('click', '.exclude', function(e) {
231 e.preventDefault();
232 var el = $(this);
233 var excluded_file = get_excluded_file(el);
234 add_excluded_js_file(excluded_file);
235 tab_need_saving('js');
236 highlight_excluded_item(el);
237 });
238
239 // Handle css excludes
240 $('#wpo_min_cssprocessed').on('click', '.exclude', function(e) {
241 e.preventDefault();
242 var el = $(this);
243 var excluded_file = get_excluded_file(el);
244 add_excluded_css_file(excluded_file);
245 tab_need_saving('css');
246 highlight_excluded_item(el);
247 });
248
249 /**
250 * Get excluded file url
251 *
252 * @param {HTMLElement} el
253 *
254 * @return {string}
255 */
256 function get_excluded_file(el) {
257 return el.data('url');
258 }
259
260 /**
261 * Exclude js file
262 *
263 * @param {string} excluded_file File url
264 */
265 function add_excluded_js_file(excluded_file) {
266 var $js_textarea = $('#exclude_js');
267 var list_of_excluded_files = $js_textarea.val();
268 list_of_excluded_files += excluded_file + '\n';
269 $js_textarea.val(list_of_excluded_files);
270 }
271
272 /**
273 * Exclude css file
274 *
275 * @param {string} excluded_file File url
276 */
277 function add_excluded_css_file(excluded_file) {
278 var $css_textarea = $('#exclude_css');
279 var list_of_excluded_files = $css_textarea.val();
280 list_of_excluded_files += excluded_file + '\n';
281 $css_textarea.val(list_of_excluded_files);
282 }
283
284 // Handle defer
285 $('#wpo_min_jsprocessed').on('click', '.defer', function(e) {
286 e.preventDefault();
287 add_deferred_file($(this));
288 });
289
290 // Handle async loading
291 $('#wpo_min_cssprocessed').on('click', '.async', function(e) {
292 e.preventDefault();
293 add_async_file($(this));
294 });
295
296 /**
297 * Add deferred file
298 *
299 * @param {HTMLElement} el target element
300 */
301 function add_deferred_file(el) {
302 var deferred_file = el.data('url');
303 var $async_js_textarea = $('#async_js');
304 var list_of_deferred_files = $async_js_textarea.val();
305 list_of_deferred_files += deferred_file + '\n';
306 $async_js_textarea.val(list_of_deferred_files);
307 tab_need_saving('js');
308 highlight_excluded_item(el);
309 }
310
311 /**
312 * Add asynchronously loading file
313 *
314 * @param {HTMLElement} el target element
315 */
316 function add_async_file(el) {
317 var async_file = el.data('url');
318 var $async_css_textarea = $('#async_css');
319 var list_of_async_files = $async_css_textarea.val();
320 list_of_async_files += async_file + '\n';
321 $async_css_textarea.val(list_of_async_files);
322 tab_need_saving('css');
323 highlight_excluded_item(el);
324 }
325
326 /**
327 *
328 * @param {string} tab_name Name of the tab that need saving
329 */
330 function tab_need_saving(tab_name) {
331 $('#wp-optimize-nav-tab-wpo_minify-' + tab_name + '-contents form').data('need_saving', true);
332 }
333
334 /**
335 * Update UI after excluding the file
336 *
337 * @param {HTMLElement} el Target element
338 */
339 function highlight_excluded_item(el) {
340 el.closest('.wpo_min_log').prev().removeClass('hidden').addClass('updated').slideDown();
341 el.text(wpoptimize.added_to_list);
342 el.removeClass('exclude');
343 el.parent().addClass('disable-list-item');
344 el.replaceWith($('<span>' + el.text() + '</span>'));
345 }
346
347 $('#wp-optimize-minify-advanced').on('click', '.save-exclusions', function(e) {
348 e.preventDefault();
349 $('.wp-optimize-save-minify-settings').first().trigger('click');
350 });
351
352 // Set the initial `enabled` value
353 this.enabled = $('#wpo_min_enable_minify').prop('checked');
354 $(document).trigger('wp-optimize/minify/toggle-status', {enabled: this.enabled});
355
356 // When loading the page and minify is disabled, make sure that the status tab is active.
357 if (!this.enabled && !$('#wp-optimize-nav-tab-wrapper__wpo_minify a[data-tab="status"]').is('.nav-tab-active')) {
358 $('#wp-optimize-nav-tab-wrapper__wpo_minify a[data-tab="status"]').trigger('click');
359 }
360
361 // Enable / disable defer_jquery
362 function check_defer_status( e ) {
363 $('input[name="enable_defer_js"]').each(function(index, element) {
364 $(element).closest('fieldset').removeClass('selected').find('.defer-js-settings').slideUp('fast');
365 });
366 $('input[name="enable_defer_js"]:checked').closest('fieldset').addClass('selected').find('.defer-js-settings').slideDown('fast');
367 }
368
369 $('input[name="enable_defer_js"]').on('change', check_defer_status);
370
371 check_defer_status();
372
373 /**
374 * Minify Preloader functionality
375 */
376 var run_minify_preload_btn = $('#wp_optimize_run_minify_preload'),
377 minify_preload_status_el = $('#wp_optimize_preload_minify_status'),
378 check_status_interval = null;
379
380 run_minify_preload_btn.on('click', function() {
381 var btn = $(this),
382 is_running = btn.data('running'),
383 status = minify_preload_status_el.text();
384
385 btn.prop('disabled', true);
386
387 if (is_running) {
388 btn.data('running', false);
389 clearInterval(check_status_interval);
390 check_status_interval = null;
391 send_command(
392 'cancel_minify_preload',
393 null,
394 function(response) {
395 if (response && response.hasOwnProperty('message')) {
396 minify_preload_status_el.text(response.message);
397 }
398 }
399 ).always(function() {
400 btn.val(wpoptimize.run_now);
401 btn.prop('disabled', false);
402 });
403 } else {
404 minify_preload_status_el.text(wpoptimize.starting_preload);
405 btn.data('running', true);
406 send_command(
407 'run_minify_preload',
408 null,
409 null,
410 true,
411 {
412 timeout: 3000 // set a timeout in case the server doesn't support our close browser connection function.
413 }
414 ).always(function(response) {
415 try {
416 var resp = wpo_parse_json(response);
417 } catch (e) {
418 }
419
420 if (resp && resp.error) {
421
422 var error_text = wpoptimize.error_unexpected_response;
423
424 if (typeof resp.error != 'function') {
425 error_text = resp.error;
426 } else if (resp.status) {
427 error_text = resp.status + ': ' + resp.statusText;
428 }
429
430 alert(error_text);
431
432 minify_preload_status_el.text(status);
433 btn.prop('disabled', false);
434 btn.data('running', false);
435
436 return;
437 }
438
439 minify_preload_status_el.text(wpoptimize.loading_urls);
440 btn.val(wpoptimize.cancel);
441 btn.prop('disabled', false);
442 run_update_minify_preload_status();
443 });
444 }
445 });
446
447 /**
448 * If already running then update status
449 */
450 if (run_minify_preload_btn.data('running')) {
451 run_update_minify_preload_status();
452 }
453
454 /**
455 * Create interval action for update preloader status.
456 *
457 * @return void
458 */
459 function run_update_minify_preload_status() {
460 if (check_status_interval) return;
461
462 check_status_interval = setInterval(function() {
463 update_minify_preload_status();
464 }, 5000);
465 }
466
467 /**
468 * Update minify preload status ajax action.
469 *
470 * @return void
471 */
472 function update_minify_preload_status() {
473 send_command('get_minify_preload_status', null, function(response) {
474 if (response.done) {
475 run_minify_preload_btn.val(wpoptimize.run_now);
476 run_minify_preload_btn.data('running', false);
477 clearInterval(check_status_interval);
478 check_status_interval = null;
479 } else {
480 run_minify_preload_btn.val(wpoptimize.cancel);
481 run_minify_preload_btn.data('running', true);
482 }
483 minify_preload_status_el.text(response.message);
484 update_minify_size_information(response);
485 });
486 }
487
488 /**
489 * Run update information about minify size.
490 *
491 * @return void
492 */
493 function update_minify_size_information(response) {
494 $('#wpo_min_cache_size').text(response.size);
495 $('#wpo_min_cache_total_size').text(response.total_size);
496 }
497 return this;
498 }
499
500 /**
501 * Get the list of files generated by Minify and update the markup.
502 */
503 minify.getFiles = function() {
504 // Only run if the feature is enabled
505 if (!this.enabled) return;
506
507 var data = {
508 stamp: new Date().getTime()
509 };
510
511 send_command('get_minify_cached_files', data, function(response) {
512 minify.updateFilesLists(response);
513 minify.updateStats(response);
514 });
515
516 if (refresh_frequency) setTimeout(minify.getFiles.bind(this), refresh_frequency);
517 }
518
519 minify.updateFilesLists = function(data) {
520 if (null === data) return;
521 // reset
522 var wpominarr = [];
523
524 // js
525 if (data.js.length > 0) {
526 $(data.js).each(function () {
527 wpominarr.push(this.uid);
528 if ($('#'+this.uid).length == 0) {
529 $('#wpo_min_jsprocessed ul.processed').append('\
530 <li id="'+this.uid+'">\
531 <span class="filename"><a href="'+this.file_url+'" target="_blank">'+this.filename+'</a> ('+this.fsize+')</span>\
532 <a href="#" class="log">' + wpoptimize.toggle_info + '</a>\
533 <a href="#" class="delete-file" data-filename="' + this.filename + '">' + wpoptimize.delete_file + '</a>\
534 <div class="hidden save_notice">\
535 <p>' + wpoptimize.added_notice + '</p>\
536 <p><button class="button button-primary save-exclusions">' + wpoptimize.save_notice + '</button></p>\
537 </div>\
538 <div class="hidden wpo_min_log">'+this.log+'</div>\
539 </li>\
540 ');
541 }
542 });
543 }
544
545 $('#wpo_min_jsprocessed ul.processed .no-files-yet').toggle(!data.js.length);
546
547 // css
548 if (data.css.length > 0) {
549 $(data.css).each(function () {
550 wpominarr.push(this.uid);
551 if ($('#'+this.uid).length == 0) {
552 $('#wpo_min_cssprocessed ul.processed').append('\
553 <li id="'+this.uid+'">\
554 <span class="filename"><a href="'+this.file_url+'" target="_blank">'+this.filename+'</a> ('+this.fsize+')</span>\
555 <a href="#" class="log">' + wpoptimize.toggle_info + '</a>\
556 <a href="#" class="delete-file" data-filename="' + this.filename + '">' + wpoptimize.delete_file + '</a>\
557 <div class="hidden save_notice">\
558 <p>' + wpoptimize.added_to_list + '</p>\
559 <p><button class="button button-primary save-exclusions">' + wpoptimize.save_notice + '</button></p>\
560 </div>\
561 <div class="hidden wpo_min_log">'+this.log+'</div>\
562 </li>\
563 ');
564 }
565 });
566 }
567
568 $('#wpo_min_cssprocessed ul.processed .no-files-yet').toggle(!data.css.length);
569
570 // Remove <li> if it's not in the files array
571 $('#wpo_min_jsprocessed ul.processed > li, #wpo_min_cssprocessed ul.processed > li').each(function () {
572 if (-1 == jQuery.inArray($(this).attr('id'), wpominarr)) {
573 if (!$(this).is('.no-files-yet')) {
574 $(this).remove();
575 }
576 }
577 });
578 };
579
580 minify.updateStats = function(data) {
581 if (data.cachesize.length > 0) {
582 $("#wpo_min_cache_size").html(this.enabled ? data.cachesize : wpoptimize.no_minified_assets);
583 $("#wpo_min_cache_total_size").html(this.enabled ? data.total_cache_size : wpoptimize.no_minified_assets);
584 $("#wpo_min_cache_time").html(this.enabled ? data.cacheTime : '-');
585 $("#wpo_min_cache_path").html(data.cachePath);
586 }
587 };
588
589 /**
590 * Gather data from the given form
591 *
592 * @param {HTMLFormElement} form
593 *
594 * @returns {Array} Array of collected data from the form
595 */
596 function gather_data(form) {
597 var data = $(form).serializeArray().reduce(form_serialize_reduce_cb, {});
598 $(form).find('input[type="checkbox"]').each(function (i) {
599 var name = $(this).prop("name");
600 if (name.includes('[]')) {
601 if (!$(this).is(':checked')) return;
602 var newName = name.replace('[]', '');
603 if (!data[newName]) data[newName] = [];
604 data[newName].push($(this).val());
605 } else {
606 data[name] = $(this).is(':checked') ? 'true' : 'false';
607 }
608 });
609 return data;
610 }
611
612 /**
613 * Reduces the form elements array into an object
614 *
615 * @param {Object} collection An empty object
616 * @param {*} item form input element as array element
617 *
618 * @returns {Object} collection An object of form data
619 */
620 function form_serialize_reduce_cb(collection, item) {
621 // Ignore items containing [], which we expect to be returned as arrays
622 if (item.name.includes('[]')) return collection;
623 collection[item.name] = item.value;
624 return collection;
625 }
626
627 // Gather minify settings from all tabs
628 wp_optimize.minify_settings = function() {
629 var tabs = $('[data-whichpage="wpo_minify"] .wp-optimize-nav-tab-contents form');
630 var data = {}
631 tabs.each(function() {
632 var tab = $(this);
633 data = Object.assign(data, gather_data(tab));
634 });
635 return data;
636 }
637
638 wp_optimize.minify = minify;
639
640 })(jQuery);
641