MODX insert Snippet - CSS & JS for Specific Users

Jul 22, 2013

What's "Cowboy Coding"?

Let's say you're tweaking the CSS/JS on a Live site, but you don't want visitors to see your changes until you're done. It's a minor change, so rather than spin up a whole new development environment, you create a "Test" resource and inject your CSS/JS links into that page. When you're done, you "flip the switch". Then you realize half the pages are borked because your changes collide with some other CSS/JS you didn't account for. Rinse, repeat until your changes are integrated nicely.

Don't Do That!

There's a better way. Well, there's lots of better ways, but here's one: use the "insert" Snippet :) In the default 'production' mode, this Snippet inserts CSS, JS and/or HTML at the end of the head element or body element of the document, depending on the properties passed to it. In 'dev' mode, it optionally inserts alternate content only for specific Users with a valid session in the specified Contexts.

If you configure the Snippet as such, only you see the changes you make to your CSS/JS and you can preview the entire Live site using those assets, before "flipping the switch". Now you can Cowboy Code in comfort :P

The Catch

To use it in 'dev' or 'override' mode, you must call the "insert" Snippet un cacheable, so that each request is validated, based on the Snippet properties you set, for whom should see what. This may not play nice with certain caching mechanisms like statcache and getCache. It would be advised to call the snippet cached in 'production' mode for production. ****NOTE: Be careful NOT to call the Snippet cached in 'dev' mode, because you may inadvertently cache your alternate content and display it for all users!**

The "insert" Snippet can be downloaded from the MODX Extras repo...oh, and...MODX ROCKS!