I have recently begun working on a SPA app that uses Durandal.js. We have several views and models which are composed/loaded at different times into the app.
For example: MyFavorites.js + MyFavorites.html
Is there a way to somehow have durandal "link" a view to a css file (maybe MyFavorites.css in this case) so that it could get it as needed and potentially take advantage of caching? I could put a or tag directly in my html file, but am under the impression that it is a bad practice.
Durandal doesn't have anything specifically for this. However, there is a require.js css loader plugin which you could use from one of your js modules which are associated with the functionality. I think there are some "gotchas" with doing this, but it's worth looking into if you really want dynamic css injection.
I have created a plugin. You can use it for Durandal 2.0.
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();
}
};
});
And you can use it as below in your viewmodel.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With