Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically import css with backbone?

I'm developing a app, using backbone, underscore, and jquerymobile. Following jqmobile's way, I have an index page which loads every visited page in special divs tags, flagged with the attribute data-role="page". For each page, i have its corresponding style file (or code snippet embedded in a style html tag). My problem is that the names of my stylable stuff started to collide. Other thing is that I would not like unnecessary style files loaded for each page. Is there any way of dynamically import only the required css for the current page?

like image 357
Throoze Avatar asked Apr 25 '26 11:04

Throoze


1 Answers

I am accomplishing exactly what you ask using RequireJS and the RequireCSS plugin.

Here is a snippet from one of my views:

define([
  'jquery',
  'underscore',
  'backbone',
  'views/company/form',
  'text!templates/company/company.html',
  'css!../../../css/company/company',
], function($, _, Backbone, Form, pageTemplate) {

  var Page = Backbone.View.extend({
    ...
  });

  return Page;

});

Line 7, 'css!../../../css/company/company' is where the css file becomes a requirement for loading this view.

Once the company.css stylesheet is loaded, it's in the browser even when other "pages" load because there are no actual page refreshes. Thus I have my main page views toggle a class on the <html> element:

// remove any old route-* classes existing on the html element
$('html').removeClassRegEx(/^route-.*/);
// add in the company's top-level class name
$('html').addClass('route-company');

And all my page-specific styles for the company page are scoped to the .route-company class.

You can find the jQuery plugin removeClassRegEx here.

like image 57
Jonathan Beebe Avatar answered Apr 28 '26 09:04

Jonathan Beebe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!