Managing Css Files in Durandal 2.0


Durandal does not have a mechanism to manage css file for each view. So I have created a plugin to manage css files.

The plugin is as below. I have placed this plugin under durandal/plugins folder


define(['jquery'], function ($) {
 return {
    loadCss : function (fileName) {
	var cssTag = document.createElement("link")
	cssTag.setAttribute("rel", "stylesheet")
	cssTag.setAttribute("type", "text/css")
	cssTag.setAttribute("href", fileName)
	cssTag.setAttribute("class", "__dynamicCss")

	document.getElementsByTagName("head")[0].appendChild(cssTag)
	},
	removeModuleCss: function () {
	$(".__dynamicCss").remove();

	}
  };
});

In the viewmodel, I have used is as below.


define(['plugins/cssLoader'], function (cssLoader) {
  var ctor = function () {
	this.compositionComplete = function () {
	  cssLoader.loadCss("sample.css");
      cssLoader.loadCss("sample2.css");
 	};
    this.deactivate =  function () {
    cssLoader.removeModuleCss();
    }
  };

  return ctor;
});

1 comment

Anonymous said...

Thanks for this.
An acceptable workaround in some cases.
The only thing I'd change - I'd load CSS from Activate, not CompositionComplete.
This will lower glitch on a transition between views.

Powered by Blogger.