David Karich

Module: AIOM+ (All In One Minify) for CSS, LESS, JS and HTML

171 posts in this topic

Hey guys, 

first, ProcessWire is a great piece of software. Thanks for that and the great community behind that. So, i'm realy new to ProcessWire, but i will present you my first module for SEO- and performance optimizing: AIOM+ (All In One Minify).

AIOM+ (All In One Minify) for CSS, LESS, JS and HTML

AIOM+ (All In One Minify) is a module to easily improve the performance of your website. By a simple function call Stylesheets, LESS and Javascript files can be parsed, minimized and combined into one single file. This reduces the server requests, loading time and minimizes the traffic. In addition, the generated HTML source code can be minimized and all generated files can be loaded over a cookieless domain (domain sharding).

Install AIOM+

  1. Download current release (link below)
  2. Extract and copy the files for this module to /site/modules/AllInOneMinify/
  3. Login to PW backend and go to Modules > Check for new modules
  4. Install Module > AIOM+ (All In One Minify) for CSS, LESS, JS and HTML

Alternative in ProcessWire 2.4

  1. Login to PW backend and go to Modules
  2. Click tab "new" and enter Module Class Name: "AllInOneMinify"
  3. Click "Download and Install"

Features

  • Combining stylesheets / LESS files or JavaScripts
  • Minimize the combined files
  • No change to the .htaccess necessary (except for the domain sharding)
  • Server-side LESS parsing without plugins
  • HTML source code minimization
  • Cookieless domain / domain sharding
  • Automatic cache management (With changes to the source file, the cache is rebuilt)
  • Configurable via the backend
  • Automatic rewriting the paths in the stylesheet and LESS files. No changes are needed
  • Optional developer mode (combining, but no minimize and browser cache prevention)
  • Clear the cache on the backend
  • Conditional loading for CSS, LESS and JS (since Version 3.1.1)

How to use

Minimize multiple stylesheet or LESS files into one file. You can even mix stylesheet and LESS files in parsing and combining process!

<link rel="stylesheet" href="<?php echo AIOM::CSS(array('css/file-1.css', 'css/file-2.less', 'css/file-3.css', 'css/file-4.less')); ?>"> 

Minimize multiple javascript files into one file.

<script src="<?php echo AIOM::JS(array('js/file-1.js', 'js/file-2.js', 'js/file-3.js', 'js/file-4.js')); ?>"></script>

Conditional loading (same with Javascripts)

<?php $stylesheets  = array('css/reset.css',
                            'css/main.less',
                            array('loadOn'  => 'id|template=1002|1004|sitemap', // PW API selector
                                  'files'   => array('css/special.css', 'css/special-theme.less'))); ?>

<link rel="stylesheet" type="text/css" href="<?php echo AIOM::CSS($stylesheets); ?>" /> 

More Information, Documentation and Download

So, I hope you can do something with this module. :)

Dave

post-1973-0-08441200-1393031073_thumb.pn

26 people like this

Share this post


Link to post
Share on other sites

Welcome to processwire cmp* and the forum David. And thanks for making your aiom+ module.

Looking at that module you must already be an experienced coder and so you don't need much

introduction to the how's and what's. But maybe you still may find something usefull in this channel:

http://processwire.com/talk/topic/4173-grouped-forum-posts-links-articles-tutorials-code-snippets/

(* = content management potential)

Share this post


Link to post
Share on other sites

I really like all the minify and less support. Actually I use the Spex-Module from Jonathan. With the next project I want to use AIOM+.

Looks good. I really like the idea of domain sharding built in.

 
Only one question for me is if it is an improvement to use domain sharding today. Before 2010, max 2 simultaneous connections was allowed. Today 6-8 are allowed/used. Without images you may need 1 html + 1 css + 1 js + 1 optional for Fonts = 4
 
related article: http://www.mobify.com/blog/domain-sharding-bad-news-mobile-performance/

Share this post


Link to post
Share on other sites

Yep, easily one of the most useful PW modules around. It fits great into my workflow, and now with version 3.0 and the added LESS support it gets even better. Keep up the good work!

PS Have you guys considered adding Autoprefixer support to the module (maybe as an option)? I'm not sure if this is easy to implement but it saves people the hassle of writing all kinds of vendor prefixes in their CSS, and instead just automatically takes care of this.

2 people like this

Share this post


Link to post
Share on other sites

Thank you very much for the module, it is one of my favorites. I have started a topic on github suggesting the use of conditional loading for files using the ID of the page.

I did not know existed the PHP official version of LESS, although I had already used to using koala (http://koala-app.com/) :)

Share this post


Link to post
Share on other sites

Thank you guys, for this great feedback. That make me happy. :)

Yep, easily one of the most useful PW modules around. It fits great into my workflow, and now with version 3.0 and the added LESS support it gets even better. Keep up the good work!

PS Have you guys considered adding Autoprefixer support to the module (maybe as an option)? I'm not sure if this is easy to implement but it saves people the hassle of writing all kinds of vendor prefixes in their CSS, and instead just automatically takes care of this.

I do not think it's the best way, to integrate Autoprefixer in AIOM+. I think it's not good when the module changes the generated code, which can be difficult to understand. Makes it difficult for the troubleshooting. But I'll be looking at Autoprefixer. Maybe I can port the code to PHP.

Currently i use LESS for that: 

.transition(@style) {
    -webkit-transition: @style;
    -moz-transition: @style;
    -o-transition: @style;
    -ms-transition: @style;
    transition: @style;
}

#element {
    .transition(all 0.2s ease);
}

Thank you very much for the module, it is one of my favorites. I have started a topic on github suggesting the use of conditional loading for files using the ID of the page.

I did not know existed the PHP official version of LESS, although I had already used to using koala (http://koala-app.com/) :)

Excellent suggestion! I'm still thinking about the syntax, but definitely write this function on the To-Do. Thank you.

Share this post


Link to post
Share on other sites

I really like all the minify and less support. Actually I use the Spex-Module from Jonathan. With the next project I want to use AIOM+.

Only one question for me is if it is an improvement to use domain sharding today. Before 2010, max 2 simultaneous connections was allowed. Today 6-8 are allowed/used. Without images you may need 1 html + 1 css + 1 js + 1 optional for Fonts = 4

related article: http://www.mobify.com/blog/domain-sharding-bad-news-mobile-performance/

I think for websites and applications that are designed for desktop systems, domain sharding is still acute and helpful. For mobile-optimized sites, it is counterproductive. 
 
The DNS overhead, is however, in my experience, not in comparison with the cookie data. For large news portals I continued domain sharding in use.
1 person likes this

Share this post


Link to post
Share on other sites

AIOM+ now in Version 3.0.1 with a little but recommended fix in the Less parser. If a large LESS file is split by the parser, the following error occurs: 

Error: Class 'Less_Exception_Parser' not found (line 8795 of /site/modules/AllInOneMinify/lib/Less/Less.php)

Issue found and submited by Ryan Pierce. Thanks.

Share this post


Link to post
Share on other sites

Hey David, really like AIOM. I would usually use Assetic for that, and I think you might want to look at integrating that code. Could save you a few headaches.  :)

Share this post


Link to post
Share on other sites

Hey David, really like AIOM. I would usually use Assetic for that, and I think you might want to look at integrating that code. Could save you a few headaches.  :)

Hey Pierre, 

I'm not really happy with Assetic for several reasons: 

  • Too many dependencies.
  • Java-based YUI integeration. Many shared hosting do not offer Java support.
  • Depending on the Google Closure API. I don't wanted to integrate any third party service.
  • Node.js for LESS parser, because the PHP-ported version in Asettic is outdated and is no longer developed and supported.

In summary, you could not just use AIOM+ as it is now – install and use. AIOM+ requires only PHP and is not dependent on another service or special server requirements. :)

1 person likes this

Share this post


Link to post
Share on other sites

So, just before the weekend, I've uploaded a new version (3.1.1) that supports a new feature: Conditional loading. You can now assign CSS, LESS or JS files with an API-selector a condition at which they should be loaded. For example: 

<?php $stylesheets  = array('css/reset.css',
                            'css/main.less',
                            array('loadOn'  => 'id|template=1002|1004|sitemap', // PW API selector
                                  'files'   => array('css/special.css', 'css/special-theme.less'))); ?>

<link rel="stylesheet" type="text/css" href="<?php echo AIOM::CSS($stylesheets); ?>" /> 
10 people like this

Share this post


Link to post
Share on other sites

Hi, one quick question: Is there a way to set it up that it cleans the HTML but leaves the line breaks intact?

So I see a clean, neat website source code without spaces and comments but the code is not squeezed into one single endless line?

Share this post


Link to post
Share on other sites

Hi, one quick question: Is there a way to set it up that it cleans the HTML but leaves the line breaks intact?

So I see a clean, neat website source code without spaces and comments but the code is not squeezed into one single endless line?

Doesn't this kind of defeat the purpose of minimizing your html? If you want to look at nicely formatted source every browser nowadays has a good or decent devtools/inspector.

2 people like this

Share this post


Link to post
Share on other sites

I do not think those extra few carriage returns matter too much.

Planning the "presentation" of source code is for psychological reasons: e.g. if 3rd parties (clients?) look at the code.

So, the "purpose" of minimizing html may vary from user to user. :-)

Share this post


Link to post
Share on other sites

What's stopping a client from opening devtools? If clients care enough to look at source code and actually base an opinion (negative or positive) on that, i think they are well aware of optimizations like minimize and they actually applaud you for that, or you could tell them: "we minimize (and concatenate) the output for optimal performance, especially on mobile". Keeping cr/lf in there seems an in-between, for no real reason. To me minimize means minimize, but to each it's own i guess.

3 people like this

Share this post


Link to post
Share on other sites

Hi, one quick question: Is there a way to set it up that it cleans the HTML but leaves the line breaks intact?

So I see a clean, neat website source code without spaces and comments but the code is not squeezed into one single endless line?

Hi ceberlin, 
 
no, there is no option, because this ist not the target of a minimization. Every browser has an inspector or dev-tools in which you or your client can see the restructured DOM.

Share this post


Link to post
Share on other sites

Hi David,

I've been playing around with bower to manage third party libraries, bower puts files in a directory called bower_components and my first instinct was to put that directory right in "site/". In _getFileInfoArray any attempt to reference a file outside the templates directory gets thwarted, is there a security concern here?

Share this post


Link to post
Share on other sites

I read the module description and it looks like a great minify solution! Is there an overhead because of caching and cache rebuild? For example with a slow first page load or will the cache created prior to the first visitor? How do you monitor file changes?

I'll try AIOM+ soon to minify html, css and js with a new PW website :)

Share this post


Link to post
Share on other sites

Hi David,

I've been playing around with bower to manage third party libraries, bower puts files in a directory called bower_components and my first instinct was to put that directory right in "site/". In _getFileInfoArray any attempt to reference a file outside the templates directory gets thwarted, is there a security concern here?

Hi Jonathan , 

yes, in this function paths are filtered to prevent directory traversal attacks. AIOM+ loads only allowed files that are located in the template folder. I think about it, in one of the upcoming versions, introduce a whitelist for asset folder.

For a workaround change the following line (749) in AllInOneMinify.module

$_path  = str_ireplace(array('../', './', '%2e%2e%2f', '..%2F'), '', (wire('config')->paths->templates.$_file));

to 

$_path  = wire('config')->paths->templates.$_file; 

I have not tested it and I can not recommend it too.

1 person likes this

Share this post


Link to post
Share on other sites

I read the module description and it looks like a great minify solution! Is there an overhead because of caching and cache rebuild? For example with a slow first page load or will the cache created prior to the first visitor? How do you monitor file changes?

I'll try AIOM+ soon to minify html, css and js with a new PW website :)

Hi pwFoo, 

AIOM+ monitors each asset file on the modifikation time and generates a hash for the comparsion with the already cached files. If there exist no cached file, the first function call will trigger that process, but only for files, that are needed (first page load). The average overhead of an average webproject on shared hosting with 128 MB php_memory_limit are round 500 ms for generating, minimization, parsing and writing the cached files. That's at least my experience. The complete Bootstrap 3 source as LESS files is generated in under 3 seconds.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      First a note about my other modules...
      I have three existing modules that are similar in that they allow restrictions to be placed on repeating inputfields: Limit Repeater, Limit PageTable, Limit Table
      Restrict Repeater Matrix takes a different approach to the module configuration from those other modules. The module settings for Restrict Repeater Matrix are applied in the field settings rather in a module config screen. I think this new approach is better, but it means that it isn't practical to create different settings for different roles via the admin interface. Instead the module has a hookable method, allowing roles to be targeted and other advanced usages to be achieved via a hook. The result is that the module is more flexible.
      I intend to transition my other modules to the same approach over the coming weeks, but because this will result in breaking changes I will be releasing the updated modules under new names ("Restrict Repeater", etc) to avoid users upgrading via the Upgrades module without full awareness of the changes. The old modules will be marked as deprecated.
       
      Restrict Repeater Matrix
      A module for ProcessWire CMS/CMF. Allows restrictions and limits to be placed on Repeater Matrix fields.
      For any matrix type in a Repeater Matrix field you have the option to:
      Prevent drag-sorting of items Prevent cloning of items Prevent toggling of the published state of items Prevent trashing of items Limit the number of items that may be added to the inputfield Please note that restrictions and limits are applied with CSS/JS so should not be considered tamper-proof.
      Usage
      Install the Restrict Repeater Matrix module.
      For each matrix type created in the Repeater Matrix field settings, a "Restrictions" fieldset is added at the bottom of the matrix type settings:

      For newly added matrix types, the settings must be saved first in order for the Restrictions fieldset to appear. Set restrictions for each matrix type as needed. A limit of zero means that no items of that matrix type may be added to the inputfield.
      Setting restrictions via a hook
      Besides setting restrictions in the field settings, you can also apply or modify restrictions by hooking RestrictRepeaterMatrix::checkRestrictions. This allows for more focused restrictions, for example, applying restrictions depending on the template of the page being edited or depending on the role of the user.
      The checkRestrictions() method receives the following arguments:
      $field This Repeater Matrix field $inputfield This Repeater Matrix inputfield $matrix_types An array of matrix types for this field. Each key is the matrix type name and the value is the matrix type integer. $page The page that is open in ProcessPageEdit The method returns a multi-dimensional array of matrix types and restrictions for each of those types. An example of a returned array:

      Example hooks
      Prevent the matrix type "images_block" from being added to "my_matrix_field" in a page with the "basic-page" template:
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $page = $event->arguments('page'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && $page->template->name === 'basic-page') { $type_restrictions['images_block']['limit'] = 0; } $event->return = $type_restrictions; });  
      Prevent non-superusers from trashing any Repeater Matrix items in "my_matrix_field":
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && !$this->user->isSuperuser()) { foreach($type_restrictions as $key => $value) { $type_restrictions[$key]['notrash'] = true; } } $event->return = $type_restrictions; });  
      https://github.com/Toutouwai/RestrictRepeaterMatrix
    • By bernhard
      Hi,
      just stumbled over a little module that i built for my last project. it helped me to test performance of my rockdatatables module to generate 3000 random json datasets and i want to share it with you. maybe it saves some time for someone.
      https://gitlab.com/baumrock/RockDummyData/
      easy example:
      $rdd = $modules->get('RockDummyData'); for($i=0; $i<15; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); echo date("d.m.Y H:i:s", $dummy->timestamp) . "<br>"; } more advanced:
      $json = new stdClass(); $json->data = array(); $rdd = $modules->get('RockDummyData'); for($i=0; $i<3000; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); $obj = new stdClass(); $obj->name = $dummy->forename . ' ' . $dummy->surname; $obj->position = $dummy->job; $obj->office = $dummy->city; $obj->color = $dummy->color; $obj->start_date = new stdClass(); $obj->start_date->display = date('d.m.Y',$dummy->timestamp); $obj->start_date->sort = $dummy->timestamp; $obj->salary = rand(0,10000); $json->data[] = $obj; } echo json_encode($json); you have to store your random datasets on your own into the /data folder. there are several services for creating all kinds of random data on the web - if you know one service that allows sharing those datasets let me know and i can include common needed data into the module
    • By AndySh
      Hello!
      I need your assistance please. I purchased the module FormBuilder. Unfortunately, the module discontinued delivering customer submissions to e-mail box specified in the module settings. Direct mailing to the e-mail box works OK. The module settings stays the same and are correct, like "Send e-mail to administrator(s) is checked. The last version of FormBuilder 3.0 has been installed. Please advise how to resolve the issue becase I cannot get orders from customers anymore (((
    • By kixe
      As described in this post (https://processwire.com/talk/topic/8551-custom-urls-for-pages/?p=82742) the option 'Name Format Children' under the tab 'Family' in template settings doesn't work properly and also not as expected. I had a look inside the code and made some changes which are working properly, which offers much more options, more consistency and less code too.

      The result is the following. You have 3 Options for generating name and title, which could be combined in endless variations.
      Name is always derived from title, same like creating pages manually.
      type date: if function detects # character anywhere in the string, conversion will be: deletion of # and string will be used as format parameter for PHP date() function type field: if string is a fieldname of the parent page the value of this field will be used type string: if string doesn't fit to the 2 preceeding it will be taken as it is All parts (separated by comma) will be composed in the order of setting. You can use unlimited numbers of parts

      I made a pull request on github: https://github.com/ryancramerdesign/ProcessWire/pull/831

      Example screenshots

      Setting ...


      will result in


       
    • By kongondo
      FieldtypeRuntimeMarkup and InputfieldRuntimeMarkup
       
      Modules Directory: http://modules.processwire.com/modules/fieldtype-runtime-markup/
      GitHub: https://github.com/kongondo/FieldtypeRuntimeMarkup
       
      This module allows for custom markup to be dynamically (PHP) generated and output within a page's edit screen (in Admin).
       
      The value for the fieldtype is generated at runtime. No data is saved in the database. The accompanying InputfieldRuntimeMarkup is only used to render/display the markup in the page edit screen.
       
      The field's value is accessible from the ProcessWire API in the frontend like any other field, i.e. it has access to $page and $pages.
       
      The module was commissioned/sponsored by @Valan. Although there's certainly other ways to achieve what this module does, it offers a dynamic and flexible alternative to generating your own markup in a page's edit screen whilst also allowing access to that markup in the frontend. Thanks Valan!
       
      Warning/Consideration
      Although access to ProcessWire's Fields' admin pages is only available to Superusers, this Fieldtype will evaluate and run the custom PHP Code entered and saved in the field's settings (Details tab). Utmost care should therefore be taken in making sure your code does not perform any CRUD operations!! (unless of course that's intentional) The value for this fieldtype is generated at runtime and thus no data is stored in the database. This means that you cannot directly query a RuntimeMarkup field from $pages->find(). Usage and API
       
      Backend
      Enter your custom PHP snippet in the Details tab of your field (it is RECOMMENDED though that you use wireRenderFile() instead. See example below). Your code can be as simple or as complicated as you want as long as in the end you return a value that is not an array or an object or anything other than a string/integer.
       
      FieldtypeRuntimeMarkup has access to $page (the current page being edited/viewed) and $pages. 
       
      A very simple example.
      return 'Hello'; Simple example.
      return $page->title; Simple example with markup.
      return '<h2>' . $page->title . '</h2>'; Another simple example with markup.
      $out = '<h1>hello '; $out .= $page->title; $out .= '</h1>'; return $out; A more advanced example.
      $p = $pages->get('/about-us/')->child('sort=random'); return '<p>' . $p->title . '</p>'; An even more complex example.
      $str =''; if($page->name == 'about-us') { $p = $page->children->last(); $str = "<h2><a href='{$p->url}'>{$p->title}</a></h2>"; } else { $str = "<h2><a href='{$page->url}'>{$page->title}</a></h2>"; } return $str; Rather than type your code directly in the Details tab of the field, it is highly recommended that you placed all your code in an external file and call that file using the core wireRenderFile() method. Taking this approach means you will be able to edit your code in your favourite text editor. It also means you will be able to type more text without having to scroll. Editing the file is also easier than editing the field. To use this approach, simply do:
      return wireRenderFile('name-of-file');// file will be in /site/templates/ If using ProcessWire 3.x, you will need to use namespace as follows:
      return ProcessWire\wireRenderFile('name-of-file'); How to access the value of RuntimeMarkup in the frontend (our field is called 'runtime_markup')
       
      Access the field on the current page (just like any other field)
      echo $page->runtime_markup; Access the field on another page
      echo $pages->get('/about-us/')->runtime_markup; Screenshots
       
      Backend
       

       

       
      Frontend