Developer forum

Forum » Development » 'Inline Critical CSS' results in Razor error

'Inline Critical CSS' results in Razor error

Marie Louise Veigert
Reply

Hi,

We're developing towords optimizing pageload on all solutions with 'Inline Critical CSS'

But we are having problems with the razor engine, which is used in Dynamicweb.

We have to include some files in the <head></head> in the master.cshtml:

<script type="text/javascript">

@Include("../static/dist/js/modernizr.js")

</script>

But the razor don't like the script because it contains '@'. But we can't have '@@' in a JS file.

We get this error when including the JS file: 

Line 81: "/" is not valid at the start of a code block.  Only identifiers, keywords, comments, "(" and "{" are valid.

 

Does anyone have some similair issues? And have made a workaround ?

It's important to get better pageload and prevent users from mobile devices etc. from leaving the website. This is why we have to do this :)


Replies

 
Morten Bengtson Dynamicweb Employee
Morten Bengtson
Reply

You can make a razor function that reads the contents of the file. Here is an example (with caching):

@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.PageViewModel>
<!DOCTYPE html>
<html>
<head>
    <title>@Model.Title</title>
    <meta name="description" content="@Model.Description" />
    <meta name="keywords" content="@Model.Keywords" />
    <script>
        @ReadCachedFile("../static/dist/js/modernizr.js")
    </script>
</head>
<body>
    <div>
        @Model.Placeholder("content")
    </div>
</body>
</html>
 
@functions {
    string ReadCachedFile(string relativePath)
    {
        string content = null;
 
        var path = GetFullPath(relativePath);
        string cacheKey = string.Format("File_{0}", path);
 
        if (!Dynamicweb.Caching.Cache.Current.TryGet(cacheKey, out content))
        {
            content = ReadFile(relativePath);
 
            var cachePolicy = new Dynamicweb.Caching.CacheItemPolicy()
            {
                FileDependencies = new[] { path }
            };
 
            Dynamicweb.Caching.Cache.Current.Add(cacheKey, content, cachePolicy);
        }
 
        return content;
    }
 
    string ReadFile(string relativePath)
    {
        var path = GetFullPath(relativePath);
        string content = System.IO.File.Exists(path) ? System.IO.File.ReadAllText(path) : string.Empty;
        return content;
    }
 
    string GetFullPath(string relativePath)
    {
        return System.IO.Path.Combine(Pageview.Layout.Design.Path, relativePath);
    }
}

I'm not sure if inlining a large js library on each and every page will do any good for performance though :)

Best regards,
Morten

 

You must be logged in to post in the forum