Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulizing CSS Stylesheets with RequireJS

I have created a template like so:

// template.tpl
<div>
    <input id="an_input"></input>
</div>

and some CSS:

// stylesheet.css
input {
    background: #000000;
}

Finally this is a slimmed down module:

define([
    'jquery',
    'text!template.tpl',
    'text!styleshet.css'
], function($, html, css){      
    var view = $('#sample_div');
    view.append($(html));

    var regex = /^([^\s\}])/gm;

    var styles = css.replace(regex, '#'+view.attr('id')+' $1');
    var style = $('<style>\n'+styles+'\n</style>');
    view.prepend(style);
});

What is essentially happening, is the template is being loaded and put into the #sample_div. Shortly after the CSS file is being loaded as text, then every item is prefixed with the ID of the view.

Once the CSS is prefixed, the style tag is created and placed inside the view.

Now, this works perfectly, OK it isn't pretty, nor does it leave much margin for error. However I wrote this code to help demonstrate what I need.

I need to be able to load templates with view specific stylesheets, where the styles in the sheet will only ever apply to the view and will only override global styles.

The problem with the above example is that it is a hack, a regex against the CSS, and the building of a new style tag, this is not how I want to do it. I have been looking into javascript CSS parsers for a cleaner solution, and although JSCSSP caught my eye, it put to many functions into the global namespace, and jquery.parsecss only seems to work with styles already within the document.

Does anyone have any experience with what I am trying to achieve?

like image 427
Flosculus Avatar asked Oct 21 '22 17:10

Flosculus


1 Answers

Most loaders out there have CSS plugins that handle the insertion for you:

RequireJS CSS plugin https://github.com/tyt2y3/requirejs-css-plugin

CurlJS CSS plugin is bundled with the main distribution: https://github.com/cujojs/curl/tree/master/dist

like image 73
ddotsenko Avatar answered Oct 24 '22 10:10

ddotsenko