diff --git a/packages/subapp-web/src/index.js b/packages/subapp-web/src/index.js index 2f5582d38..ebba57afb 100644 --- a/packages/subapp-web/src/index.js +++ b/packages/subapp-web/src/index.js @@ -105,24 +105,35 @@ export function loadSubApp(info, renderStart) { return info; } -export function dynamicLoadSubApp(options) { +export function dynamicLoadSubApp({ name, id, timeout = 15000, onLoad, onError }) { // TODO: timeout and callback const wsa = window.webSubApps; - const lname = options.name.toLowerCase(); + const lname = name.toLowerCase(); if (wsa._bundles[lname] === undefined) { window.loadSubAppBundles(lname); } + const startTime = Date.now(); const load = delay => { setTimeout(() => { - const subApp = wsa[options.name]; - const element = document.getElementById(options.id); - if (element && subApp && subApp.start) { - subApp.start({ id: options.id }); - } else { - load(50); + const subApp = wsa[name]; + if (subApp) { + if (!id) { + return onLoad(); + } else { + const element = document.getElementById(id); + if (element && subApp.start) { + return subApp.start({ id }); + } + } } + + if (timeout > 50 && Date.now() - startTime > timeout) { + return onError(new Error("dynamicLoadSubApp Timeout")); + } + + return load(50); }, delay); }; diff --git a/samples/poc-subapp/src/components/deals.jsx b/samples/poc-subapp/src/components/deals.jsx index c9110858d..9f3641d96 100644 --- a/samples/poc-subapp/src/components/deals.jsx +++ b/samples/poc-subapp/src/components/deals.jsx @@ -3,6 +3,46 @@ import { dynamicLoadSubApp } from "subapp-web"; import PropTypes from "prop-types"; import { connect } from "react-redux"; +class SubApp extends React.Component { + constructor() { + super(); + this.state = { ready: false }; + } + + render() { + // is subapp loaded? + // TODO: handle SSR + if (typeof window === "undefined") { + return ""; + } + const { name } = this.props; + const wsa = window.webSubApps; + const lname = name.toLowerCase(); + + if (wsa._bundles[lname] && wsa[name]) { + const subapp = window.webSubApps[name]; + return ( +