Search code examples
asp.net-coreblazorblazor-client-sideblazor-webassembly

How to add different CSS files to different layouts in blazor?


Hi every blazor lover!

I have 2 different layouts and, I want to load different CSS file on each layout.

The first one is MainLayout.razor and the other is AdminLayout.razor.

I want to load my admin menu CSS file in the AdminLayout, without using "css isolation", because the CSS files for this layout maybe more files in future.

ASP.NET Core 3.1 or .NET 5.0

Thanks in advance.


Solution

  • Solution for .Net 3.1 or .Net 5.0

    use this java script to add css file to page or layout directly:

        function loadCss(cssPath) {
            var ss = document.styleSheets;
            for (var i = 0, max = ss.length; i < max; i++) {
                if (ss[i].href.includes(cssPath.substr(2)))
                    return;
            }
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.href = cssPath;
        
            document.getElementsByTagName("head")[0].appendChild(link);
        }
    

    I create a js function "loadCss", you have to call this function on OnAfterRenderAsync event:

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            await JsRuntime.InvokeVoidAsync("loadCss", "css/FILENAME.min.css");
        }