Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

durandal.js - is it possible to load view specific css on demand with the view?

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.

like image 572
Rob Avatar asked Dec 21 '22 07:12

Rob


2 Answers

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.

like image 164
EisenbergEffect Avatar answered May 01 '23 14:05

EisenbergEffect


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;
});
like image 33
Ibrahim ULUDAG Avatar answered May 01 '23 14:05

Ibrahim ULUDAG