Make ASP.NET bundling specify media=screen for CSS bundle

后端 未结 8 1294
情深已故
情深已故 2020-12-23 13:47

I\'m just trying out ASP.NET 4.5 bundling and minification, and ran into an issue.

I\'ve got around 10 css files, of which 2 were originally referenced in the layout

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 14:30

    I took Adam Tal's suggestion a little further.

    I'm probably over-coding it, but for readability, I created a static class to kind of mimic the Styles.Render format.

    public static class StyleExtensions
    {
        public enum Format
        {
            Async,
            Preload,
        }
    
        public static IHtmlString Render(string contentPath, Format format)
        {
            switch (format)
            {
                case Format.Async:
                return contentPath.ToAsyncFormat();
                case Format.Preload:
                return contentPath.ToPreloadFormat();
                default:
                return new HtmlString(string.Empty);
            }
        }
    
        public static IHtmlString RenderAsync(string contentPath)
        {
            return contentPath.ToAsyncFormat();
        }
    
        public static IHtmlString RenderPreload(string contentPath)
        {
            return contentPath.ToPreloadFormat();
        }
    
        public static IHtmlString ToAsyncFormat(this string contentPath)
        {
            return Styles.RenderFormat("", contentPath);
        }
    
        public static IHtmlString ToPreloadFormat(this string contentPath)
        {
            return Styles.RenderFormat("", contentPath);
        }
    }
    

    I would probably erase either the direct constructor or the enum constructor, and you could really put the string extension inside the method too, depending on whatever makes more sense to you, but you'd call it either of these ways accordingly:

    @StyleExtensions.Render("~/Content/bundle-bootstrap", StyleExtensions.Format.Preload)
    @StyleExtensions.Render("https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;700&display=swap", StyleExtensions.Format.Preload)
    @StyleExtensions.Render(Url.Content("~/Content/Styles/Primary.min.css"), StyleExtensions.Format.Async)
    

    or

    @StyleExtensions.RenderPreload("~/Content/bundle-bootstrap")
    @StyleExtensions.RenderPreload("https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;700&display=swap")
    @StyleExtensions.RenderAsync(Url.Content("~/Content/Styles/Primary.min.css"))
    

提交回复
热议问题