我正在运行一个使用服务器端渲染的 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
-<%= raw @html %>
但正如你所看到的,我已经删除了它。
所以无论如何,如果我以“合理”的速度刷新浏览器窗口,就没有问题......但如果我开始快速刷新,我可以在浏览器窗口中简要地看到未渲染的 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 后再向用户显示它?