Loading Minified CSS & JS files

Why?

Needed a way to load minified CSS & JS on live domain and un-minified CSS & JS on localhost

The How

First, create a snippet called site-cssjs.php (filename is unimportant, call it what you will).

Put the following code in the snippet:

<?php
$siteurl = $_SERVER['HTTP_HOST'];
if (strstr($siteurl, $livesite))
{
  echo css('/assets/css/site.min.css');
  echo js('/assets/js/site.min.js');
}
else
{
  echo css('/assets/css/site.css');
  echo js('/assets/js/site.js');
}
?>

Use the snippet in your template head section like so and amend it to match your live domain :

<?php snippet('site-cssjs', ['livesite' => 'yourlivedomain.com']) ?>

How does it work?

Checks to see if the variable passed on the snippet matches the domain the site is currently running on and acts accordingly.

As a bonus, you can also use this to load stuff you only want on a live site, such as Google Analytics. This will prevent false hits to the tracker during development.

If anyone has any ideas how to make this a little slicker, feel free to chime in on the replies. :slight_smile:

Have fun.

3 Likes

One alternative, if you use custom config files for your environments, you might as well set the css/js files there:

c::set('site.stylesheet', 'site.min.css');
c::set('site.js', 'site.min.js);

In your header

<?php
echo css('/assets/css/' . c::get('site.stylesheet');
echo js('/assets/css/' . c::get('site.js');
5 Likes

personally i never link unminified JS anymore but always include minified versions in combination with a sourcemap.