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

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