Jump to main content Jump to doc navigation

Learning How to Register CSS and JS

So, you've got a Snippet that you've been writing and want to add CSS and/or JavaScript to your pages, but don't want to have to setup a custom Template Variable and edit it on every Resource your Snippet is used on. You want the Snippet to do it, dagnabbit! Well, it's pretty easy, actually, using some MODX API methods.

Other CMSs This is a common need in any CMS, so if you're coming from another platform, here are some of the related functions. - WordPress – uses its wp_enqueue_script, wp_register_script, wp_enqueue_style, wp_register_style functions.

Adding to the HEAD

There are a few methods that automatically add CSS and/or JavaScript to the HEAD of the current page. They will run in the order that they're added, so if you need them in a certain order, make sure you execute the methods in that order as well.


This function lets you register any CSS file to the HEAD of the content by providing the URL in the method:


Or, more correctly, you would use the MODX_ASSETS_URL constant so your Snippet or plugin would work even on a site that was configured to use a non-standard assets location.



This function lets you register any custom JavaScript to the HEAD of the document:



This function is useful if you need to set some JS variables, or output some HTML into the HEAD:

<meta tag="here" />
<script type="text/javascript">
var myCustomJSVar = 123;

Adding Before the BODY End

There are also methods that can be used to insert Javascript or HTML at the end of every page, right before the BODY tag closes. They are often useful for custom analytics scripts, or JS that needs to be run at the body-level rather than in the HEAD.


Similar to regClientStartupScript except that it runs before the closing BODY tag:



Similar to regClientStartupHTMLBlock except that it runs before the closing BODY tag:

<div>custom stuff here</div>
<script type="text/javascript">


MODX offers Extras developers many options on how to insert custom CSS/JS into their pages at the Snippet level. However, MODX also recommends in any Extras you are distributing, to make sure inserting CSS or JS into a page is a toggleable option, so that the user can customize the content or javascript framework should they so choose.

See Also

  1. Templating Your Snippets
  2. Adding CSS and JS to Your Pages Through Snippets
  3. How to Write a Good Snippet
  4. How to Write a Good Chunk