首页 > 解决方案 > Html Widget src 出现然后在刷新时消失

问题描述

我的 HTML 脚本标签有一个 src,但随后显示小部件的 div id 出现,然后在刷新时消失。DIV 仍然存在,但它没有引入源。我不知道为什么,因为我在 Javascript 调试器中没有收到错误消息。一件奇怪的事情是它不会在 Localhost 中消失,而只会在 Azure 中消失。

刷新页面以重现问题。我正在使用 Blazor .NET Core,小部件位于:

网站: https ://markstest1.azurewebsites.net/

源文件: https ://www.climatelevels.org/graphs/js/co2.php?theme=dark-unica&pid=2degreesinstitute

源代码 Startup.cs(为站点添加了 CORS)。一个站点是http。这可能是个问题吗?

public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(//name: MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins("https://www.climatelevels.org", "http://www.2degreesinstitute.org")
                                                  .AllowAnyHeader()
                                                  .AllowAnyMethod();
                    });
            });

带有 id 的 DIV 标记到源文件。剃刀文件。

<div id="co2-widget-container"></div>

_Host.cshtml 带有标签的文件

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="_framework/blazor.server.js"></script>
    <script src="https://www.climatelevels.org/graphs/js/co2.php?theme=dark-unica&pid=2degreesinstitute"></script></script>

标签: htmlasp.net-coreblazorblazor-server-side

解决方案


现在似乎可以正确加载。答案是 Blazor 启动得太早并取消了 _Host 文件中的 javascript 加载。看来我必须将标签添加
<script src="_framework/blazor.server.js" autostart="false"></script>
到 Blazor 脚本文件中,这样它就不会启动得太快,而是让启动文件启动 Blazor。然后在加载 DOMContentLoaded 后将 src URL 更改为 Blazor.start() 调用。

<script>document.addEventListener("DOMContentLoaded", function () {
        Blazor.start().then(function () {
        var customScript = document.createElement('script');
        customScript.setAttribute('src', '//www.website...');
        document.head.appendChild(customScript);
            });
        });</script>

使用的资源链接:
https ://github.com/dotnet/aspnetcore/issues/22643
https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-5.0


推荐阅读