【问题标题】:React/Phoenix - escaping HTML will briefly flash unrendered HTML in browserReact/Phoenix - 转义 HTML 将在浏览器中短暂闪烁未渲染的 HTML
【发布时间】:2017-12-29 10:54:27
【问题描述】:

我正在运行一个使用服务器端渲染的 React/Phoenix 应用程序,我发现当我快速刷新应用程序时,我可以在一瞬间在浏览器中看到来自服务器的未渲染 HTML所有渲染正确。这只发生在转义的 HTML 上,但我想为这个应用程序使用转义的 HTML,因为我不希望浏览器认为它是安全的。这会在 Chrome 和 Firefox 中发生,但不会在 Safari 中发生。

该应用是使用 RePh 搭建的(我强烈推荐)-https://github.com/reph-stack/reph-相关的控制器是:

defmodule MyAppWeb.ReactController do
  use MyAppWeb, :controller

  def index(conn, _params) do
    initial_state = %{}
    react_stdio_args = %{
      component: Application.app_dir(:my_app, "priv/static/server/js/app.js"),
      props: %{
        "location" => conn.request_path,
        "initial_state" => initial_state
      }
    }
    {:ok, %{"html" => html}} = StdJsonIo.json_call(react_stdio_args)
    render(conn, "index.html", html: html, initial_state: initial_state)
  end
end

将数据传送到index.html.eex:

<div id="index"><%= @html %></div>
<script>__INITIAL_STATE__=<%= @initial_state |> Poison.encode! |> raw %></script>

在此脚手架的默认设置中,@html 使用raw - &lt;%= raw @html %&gt; 标记为安全 - 但正如您所见,我已将其删除。

因此,无论如何,如果我以“合理”的速度刷新浏览器窗口,就没有问题......但如果我开始快速刷新,我可以在浏览器窗口中短暂地看到未渲染的 HTML,类似于:

<div class="AppContainer wrapper" data-reactroot="" data-reactid="1" data-react-checksum="-1859726426"><header class="site-header" data-reactid="2"> etc...

不用说,如果我把raw留在里面就不会发生这种情况。我也尝试了一些其他的转义方法,例如控制器中的Phoenix.HTML.html_escape(html),但出现了同样的问题。

我想这是因为浏览器需要一秒钟的时间来正确解析和呈现转义的 HTML,并且浏览器性能的差异可以归结为不同的布局引擎(也许?)......但是我不是这方面的专家,所以我不确定。有什么方法可以强制我的应用等到 HTML 正确呈现后再向用户显示它?

【问题讨论】:

    标签: html reactjs phoenix-framework html-rendering html-escape


    【解决方案1】:

    @html 这里是一个 HTML 字符串。您不能通过删除 raw 使其“更安全”。删除raw 将转义字符串中的所有&lt;&gt;,使浏览器显示原始HTML 代码。您需要在此处使用raw 以使 SSR 正常工作。如果您尝试以下操作,您会看到此行为:

    <%= raw "<strong>Raw</strong>" %>
    <%= "<strong>Escaped</strong>" %>
    

    【讨论】:

    • 谢谢 - 我显然误解了需要做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2012-07-16
    • 1970-01-01
    • 2016-05-07
    • 2021-11-14
    相关资源
    最近更新 更多