Css and Javascript guide
The Css and Javascript core modules allow you to easily work with CSS and JavaScript files in your web page project with some neat additional features:
CSS and JavaScript files are parsed as patterns.
Automatic minimization and single-request serving of multiple files.
Cached CSS and JavaScript.
Modules inject the CSS and JavaScript code they themselves.
CSS and JavaScript dependencies via modules.
Works in conjunction with HtmlDocument to automatically link the needed CSS/JavaScript resources in the HTML document.
Only the required CSS and JavaScript code is loaded.
Css and Javascript sets
When using the Css or the Javascript modules, you first define at least one set that will contain the *.css
and *.js
files you'll be using.
Sets are defined in the Css module configuration file /config/Css.config.php
and in the Javascript module configuration file /config/Javascript.config.php
.
Let's take a look at a typical Css.config.php
configuration file:
The Javascript.config.php
configuration file looks quite similar:
Each set can only load files from the directory you've configured.
You can add files to each set directly in the configuration file. Let's say we want to add the CSS file base.css
to the main
set, we would modify Css.config.php
to look like this:
You can also just set isIncludeAllFilesInDirectory
to true
, and all the *.css
files in the specified directory
will be added to the set:
This works exactly the same for the
Javascript.config.php
file.
CSS and JavaScript minification
To activate minification, set the isMinify
key to true
in the configuration file of the Css or the Javascript module:
CSS and JavaScript Caching and versioning
CSS and JavaScript are always cached automatically, and file versioning is automatically taken care of using content-based unique ids. Cherrycake ensures the browser caches the CSS and JavaScript requests, and that it is always receiving their latest versions if they have changed in the last update.
This ultimately means that you don't need to take care of implementing a caching policy or versioning for your CSS or JavaScript files, and the visitors to your website won't need to clear their caches to load the proper updated CSS and JavaScript files.
Linking the CSS and JavaScript to your HTML document
If you're using the HtmlDocument module to build your HTML document, the proper links to get the required CSS and JavaScript sets are already being added automatically to the <head>
section of the document:
If you're creating your own HTML document structure instead of using the HtmlDocument module, you can call the Css::getSetUrl and Javascript::getSetUrl methods to retrieve the proper URLs to request the CSS and JavaScript code.
A basic example of the usage of the Css module can be seen working in the Cherrycake documentation examples site.
Last updated