PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 3.2.9
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v3.2.9
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.9, at js/minify.js

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