Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Customising the CMS /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Modify Requirements function to place CSS files before closing body tag


Go to End


2 Posts   1914 Views

Avatar
_Matt

Community Member, 29 Posts

8 April 2014 at 8:11pm

I'm wondering if anyone can help me modify the Requirements function to allow the placement of CSS files before the closing body tag. I know there's an option to do this for Javascript files, so I'm hoping extending this to CSS files shouldn't be too tricky.

"Why", you might ask? Well if you're interested here's why: https://www.youtube.com/watch?v=YV1nKLWoARQ

Suffice to say it's for performance reasons - you should only load CRITICAL assets in the head (preferably inline to reduce HTTP requests). All other assets should be loaded asynchronously or at the foot of the page.

Avatar
_Matt

Community Member, 29 Posts

8 April 2014 at 8:34pm

So for now I've written a little function to do what I wanted, which I'll put below. It would still be good to know if the Requirements function can be modified though - optimising sites for mobile is hugely important, so being able to load CSS before the closing body tag is absolutely crucial.

In Page.php:

class Page_Controller extends ContentController
{
    /**
     * addUniqueQueryString() Adds a unique query string to a file name based on its modification date
     * @param  string $filePath Path to file relative to base URL
     * @return string File name with unique query string appended, eg. `myfile.css?m=0123456789`
     */
    function addUniqueQueryString($filePath)
    {
        $fileLastModDate = filemtime(Director::baseFolder().'/'.$filePath);
        $webSiteBaseURL = Director::BaseUrl();
        return $webSiteBaseURL . $filePath . "?m=" . $fileLastModDate;
    }
}

Then in Page.ss:

    /* Site content... */
    <link rel="stylesheet" href="$addUniqueQueryString('themes/mytheme/styles/myfile.css')">
</body>