Laravel Elixir Remove CSS Comments

Have you ever wanted to strip those block comments out of your production CSS? In the past, I’ve run into issues where the CSS is not processed correctly because everything gets bumped onto the same line as Bootstrap’s block comment and it somehow things it is also commented out. No worries though if you are using Laravel Elixir (or really just the cssnano plugin):

Here is an example of how you can configure cssnano to strip all comments:

If you are just using cssnano in a non-elixir build, you can still pass the discardComments: { removeAll: true }  option to achieve the same effect.

Javascript Wait Until jQuery Loads

Ok, if you are like me, you’ve probably had the need to put a small snippet of Javascript between some <script> tags in a view. But, if the rest of your javascript is loaded somewhere in the footer of your layout, then at the point you run that embedded snippet, none of your other libraries will have been loaded.

Allow me to introduce you to a little technique that can be an interesting workaround. I can’t claim to have found this trick as I ran across it on an awesome StackOverflow answer.

Allow me to explain what is going on here.  You will notice the function is wrapped with parenthesis followed by another set of parenthesis. This is called an immediately invoked function expression (IIFE), which is a fancy way of saying that it will run automatically when the code is loaded. When it runs, it checks to see if the window.jQuery object exists and if not, it sets a timeout for 50ms and tries again. This will continuously loop until it detects that the jQuery object exists in the global namespace and will then run your code.

This doesn’t only apply to jQuery. For my use case, I had a javascript object that I needed to set a counter based on values loaded in from a form with dynamic sections. This is  how I made that work:

You will notice the {{ … }} syntax in there. That is the blade templating language in Laravel. For my use case, I needed to generate 0 to N instances of a template and keep track in javascript how many I had so that the next instance generated client side had the appropriate numbers applied to input field names. Probably not the best way to do things, but definitely functional.