In large JavaScript applications, it can be beneficial to dynamically load CSS stylesheets. For example, if a certain JavaScript widget, such as a complex grid, uses a large standalone stylesheet for its display aesthetics, it would be optimal to only load this stylesheet if the widget is in use, rather than always including the CSS source on each application load.

AMD Plugin

One way to dynamically load CSS in an AMD application is to leverage the xstyle plugin. Xstyle is a small library that provides, among other functionality, an AMD loader plugin to dynamically load CSS. It also provides a Dojo build plugin to inline these CSS stylesheets at build time to reduce HTTP requests in production. Using xstyle, a module can dynamically load a given stylesheet. To use the AMD loader plugin, use regular AMD plugin syntax, with “xstyle/css” as the plugin loader and the path to the stylesheet afterwards:

], function(){
	// ...

Build Plugin

When building an AMD Dojo application, you can inline the CSS in two ways: in the JavaScript or in the CSS itself. The easiest approach is to inline the CSS in the JavaScript. To do this, you first need to include xstyle as an AMD build plugin in your build profile:

plugins: {
	"xstyle/css": "xstyle/build/amd-css"

After including the build plugin, running the build normally without any other changes is sufficient to inline the CSS text into the JavaScript. While this method is the simplest, it is generally more desirable to keep CSS in external stylesheets and leverage the browser’s optimized patterns for stylesheet loading. To do this, you simply need to specify a target stylesheet in the layer definition in the build profile:

layers: [{
    name: "path/to/targetModule.js",
    targetStylesheet: "my-package/css/main-stylesheet.css",

When the build runs, any CSS dependencies that are encountered in modules will then be added to main-stylesheet.css (which will be created if it does not already exist), rather than inlined in the JavaScript build layer.

Learning more

We cover AMD plugins such as xstyle and more in depth in our Dojo workshops offered throughout the US, Canada, and Europe, or at your location. We also provide expert JavaScript and Dojo support and development services, to help you get the most from JavaScript, Dojo, and performance optimization of your application. Contact us to discuss how we can help.