combine server side razor boolean with client side boolean to include a link

我只是一个虾纸丫 提交于 2019-12-08 13:37:00

问题


I have a situation where I need to decide to include a html link based on client side boolean value and server side boolean value like this :

const preloadSupported = () => {
              const link = document.createElement('link');
              const relList = link.relList;
              if (!relList || !relList.supports)
                return false;
              return relList.supports('preload');
            };

if (!@Model.oldLayout && preloadSupported())
{
    <link rel="preload" href="staticResource.js" as="script" />
}

or

if (@Model.oldLayout) //server side boolean
{
    if (preloadSupported()) // client side boolean
    {
        @foreach (var url in Model.cssUrls)
        {
            <link rel="preload" href="@Html.StaticFile(url)" as="script"/>
        }
    }
    else
    {
        @foreach (var url in Model.cssUrls)
        {
            <link rel="prefetch" href="@Html.StaticFile(url)"/>
        }
    }   
}

how should I do that? I tried different variations none of them worked! thanks for your help in advance


回答1:


You need to place this code in your razor file inside your javascript tags for the client.

Pass in the urls for the scripts from the server, or hard code it in the javascript code.

<script>
    @if (!Model.OldLayout)
    {
        <text>
        if (preloadSupported())
        {
            loadScript("/scripts/script01.js");
            loadScript("/scripts/script02.js");

            function loadScript(url)
            {
                var script = document.createElement('script');
                document.head.appendChild(script);
                script.onload = function()
                {
                    // Do anything with the script here (because it's now loaded)
                };
                script.src = url;
            }
        }
        </text>
    }
</script>



回答2:


Mixing server side and client side code can be tricky. You can use rendered server side code with javascript, but it can't really work the other way around.

In your first example, the if-statement would have to be:

if (!('@Model.oldLayout' === 'True') && preloadSupported())
{
    //..link
}

The problem here is that the link wouldn't exist until the page was parsed and rendered. You could perhaps use document.write, createElement or jquery $.load() to add it, but that depends on what the external file is used for and when it has to be added.

Best bet would really be to check for "preloadSupport" earlier, or redirect the visitor if preload is supported and create a new response.



来源:https://stackoverflow.com/questions/49437508/combine-server-side-razor-boolean-with-client-side-boolean-to-include-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!