I use webpack to build chunks, to be loaded on demand (code splitting); each chunk is rendering React components into DOM elements (divs). I need HTML to create those divs: how and when should I load the corresponding HTML ? And how should I load the chunks on demand ?
I use jQuery's load
function to insert HTML from files in container divs
. In addition I put a <script>
tag to tell which chunk should be loaded but I find it clumsy and not elegant at all compared to the rest of my application code.
Is there a less brittle way to do this?
You should use require.ensure
for dynamic route loading. Even better, if you set up your project to use Webpack 2 + Tree shaking, you can use System.import
.
Here's how:
import App from 'containers/App'; function errorLoading(err) { console.error('Dynamic page loading failed', err); } function loadRoute(cb) { return (module) => cb(null, module.default); } export default { component: App, childRoutes: [ { path: '/', getComponent(location, cb) { System.import('pages/Home') .then(loadRoute(cb)) .catch(errorLoading); } }, { path: 'blog', getComponent(location, cb) { System.import('pages/Blog') .then(loadRoute(cb)) .catch(errorLoading); } } ] };
You can get the entire guide in this blog post: Automatic Code Splitting for React Router
It turns out that what I wanted to achieve can be done via react-router , simply I didn't know ;)
<Route name="app" component={require('./app.jsx')}>
<Route path="/" name="home" component={require('./homepage-container.jsx')}/>
<Route path="/otherpath" name="other" component={require('./other.jsx')}/>
... add as many routes as wanted
</Route>
The jsx files get loaded on demand, and there is no need for plain HTML as I am using react the design is that every part is a component. In this example it is enough to activate a link to #/otherpath
in order to get the other
component to be loaded as a child of the upper level component (route called app
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.