Blazor WASM 脚本标签不应放置在组件内部,因为它们无法动态更新。将脚本标签移动到index.html文件

fin*_*s10 8 .net asp.net-core blazor blazor-webassembly

我正在开发一个.Net 6 Blazor Wasm应用程序。我需要将其放置<script type="application/ld+json">在每个登陆页面组件中以获得SEO好处。

我已经在使用<HeadContent>添加其他<meta>标签<link>。因此我决定使用相同的组件来实现此目的。

但是,当我将<script>标签放入其中时<HeadContent>,我收到编译错误,如下所示,

脚本标签不应放置在组件内,因为它们无法动态更新。要解决此问题,请将脚本标记移动到“index.html”文件或其他静态位置。

为了解决这个问题,我将脚本标签添加为字符串文本,<HeadContent>如下所示,

@page "/"
@inject NavigationManager NavigationManager

<HeadContent>
   @($@"<script type=""application/ld+json"">
        {{
            ""@context"": ""https://schema.org"",
            ""@type"": ""WebSite"",
            ""publisher"": {{
                ""@type"": ""Organization"",
                ""name"": ""Page Name"",
                ""url"": ""{NavigationManager.BaseUri}"",
                ""logo"": {{
                    ""@type"": ""ImageObject"",
                    ""url"": ""{NavigationManager.BaseUri}favicon.ico"",
                    ""width"": 16,
                    ""height"": 16
                }}
            }},
            ""url"": ""{NavigationManager.BaseUri}"",
            ""mainEntityOfPage"": {{
                ""@type"": ""WebPage"",
                ""@id"": ""{NavigationManager.BaseUri}""
            }},
            ""description"": ""some good description about the page""
        }}
    </script>")
</HeadContent>
Run Code Online (Sandbox Code Playgroud)

但这会将脚本呈现为浏览器中 head 标签内的文本,如下图所示:

渲染的头部内容

这会影响SEO福利还是有更好的方法来处理这个问题?请协助。

Mis*_*goo 21

如果您确定您知道自己在做什么并且想要使用脚本标签 - 并且会彻底测试 - 您可以像这样覆盖警告

<script suppress-error="BL9992">...</script>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于您script包含 json ,所以可能没问题


Bri*_*ker 1

您正在渲染字符串而不是标记。

@(new MarkupString($@"<script type=""application/ld+json"">
        {{
            ""@context"": ""https://schema.org"",
            ""@type"": ""WebSite"",
            ""publisher"": {{
                ""@type"": ""Organization"",
                ""name"": ""Page Name"",
                ""url"": ""{NavigationManager.BaseUri}"",
                ""logo"": {{
                    ""@type"": ""ImageObject"",
                    ""url"": ""{NavigationManager.BaseUri}favicon.ico"",
                    ""width"": 16,
                    ""height"": 16
                }}
            }},
            ""url"": ""{NavigationManager.BaseUri}"",
            ""mainEntityOfPage"": {{
                ""@type"": ""WebPage"",
                ""@id"": ""{NavigationManager.BaseUri}""
            }},
            ""description"": ""some good description about the page""
        }}
    </script>"))
Run Code Online (Sandbox Code Playgroud)