简体   繁体   English

当在React中使用危险地使用SetInnerHTML时,阻止HTML在CSS之前加载

[英]Prevent html from loading before css when using dangerouslySetInnerHTML in React

I've got a React app where I need to get my header html from a third party. 我有一个React应用程序,我需要从第三方获取我的标头html。 The third party passes me an object on initialization that looks something like this: 第三方在初始化时向我传递了一个类似于以下内容的对象:

headerObj: { desktopHeaderHtml: <div>...</div>, css: <link href="www.sweetcss.com"></link }

I am trying to pass the html into my React app by using dangerouslySetInnerHTML like so: 我试图通过使用的HTML传进我的应用程序做出反应dangerouslySetInnerHTML像这样:

import React, { Fragment } from 'react'
import ProductList from './products/ProductList'

const App = (props) => {
  const desktopHeader = {__html: `${props.navigation.css}${props.navigation.desktopHeaderHtml}`}

  return (
    <Fragment>
      <div dangerouslySetInnerHTML={ desktopHeader } />
      <ProductList />
    </Fragment>
  )
}

export default App

However, my app renders the raw HTML before loading the styles, so I get a short period of time with visible unstyled HTML from the desktopHeader . 但是,我的应用程序在加载样式之前会渲染原始HTML,因此我可以在很短的时间内从desktopHeader看到可见的未样式化HTML。 Is there a way to avoid this? 有办法避免这种情况吗? I feel like I am missing something. 我觉得我想念什么。

In case someone else ever stumbles upon this, I figured out what the problem was here. 万一有人偶然发现这个问题,我想出了这里的问题所在。

The css is providing a link, and the html is just providing markup. CSS提供了一个链接,而html提供了标记。 So, when dangerouslySetInnerHTML is called, it immediately injects both, but obviously it takes a second for the css to load since the href of the link has to be executed and actually go get the css. 因此,当dangerouslySetInnerHTML调用SetInnerHTML时,它会立即同时注入两者,但是显然,加载CSS需要一秒钟,因为必须执行链接的href并实际获取CSS。 I solved this by putting the link to call the css in the raw html file so that it is called before webpack. 我通过在原始html文件中放置用于调用CSS的链接来解决此问题,以便在webpack之前调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM