更新
我访问了该网站,我确定您正在使用 Gatsby。Gatsby 使用 SSR,而 React.lazy 和 Suspense 尚未支持服务器端渲染。如果您想在服务器呈现的应用程序中进行代码拆分,则建议使用 Loadable Components,它在React文档中有一个很好的指南,用于捆绑拆分和服务器端渲染。
有一个 Gatsby 插件可以使您的生活更轻松:gatsby-plugin-loadable-components-ssr。安装并配置插件后,您可以像这样使用loadable
:
AmazonFrame.js
import React from "react";
const AmazonFrame = ({ src, width, height }) => (
<iframe src={src} width={width} height={height} scrolling="no"></iframe>
);
App.js
import React from "react";
import loadable from "@loadable/component";
const AmazonFrame = loadable(() => import("./AmazonFrame"), {
fallback: <div>Loading...</div>
});
function App() {
return (
<div>
<AmazonFrame src="src" width="100%" height="200px" />
</div>
);
}
export default App;
或者
import React from "react";
import loadable from "@loadable/component";
const AmazonFrame = loadable(() => import("./AmazonFrame"));
function App() {
return (
<div>
<AmazonFrame fallback={<div>Loading...</div>} />
</div>
);
}
export default App;
您需要使用
代码分割。 代码分割是一种由打包工具(如Webpack,Rollup和Browserify(通过factor-bundle))支持的功能,它可以创建多个包,这些包可以在运行时动态加载。
如果您正在使用Create React App,则已为您配置此功能,您可以立即开始使用它。
将应用程序进行代码分割可以帮助您“延迟加载”用户当前需要的内容,从而显着提高应用程序的性能。虽然您没有减少应用程序中的总代码量,但您已避免了加载用户可能永远不需要的代码,并减少了初始加载期间所需的代码量。
以下是解决您问题的示例解决方案,它将延迟加载Amazon广告
iframe
,因此它不会随您的初始捆绑包一起加载:
AmazonFrame.js
import React from "react";
const AmazonFrame = ({ src, width, height }) => (
<iframe src={src} width={width} height={height} scrolling="no"></iframe>
);
export default AmazonFrame;
App.js
import React, { Suspense, lazy } from "react";
const AmazonFrame = lazy(() => import("./AmazonFrame"));
function App() {
return (
<div>
{/* The lazy component should then be rendered inside a Suspense component, which allows us to show some fallback
content (such as a loading indicator) while we’re waiting for the lazy component to load */}
{/* The fallback prop accepts any React elements that you want to render while waiting for the component to load */}
<Suspense fallback={<div>Loading...</div>}>
<AmazonFrame src="src" width="100%" height="200px" />
</Suspense>
</div>
);
}
export default App;