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
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.
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:
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.