微前端無界機制淺析

京東雲技術團隊發表於2023-11-06

簡介

隨著專案的發展,前端SPA應用的規模不斷加大、業務程式碼耦合、編譯慢,導致日常的維護難度日益增加。同時前端技術的發展迅猛,導致功能擴充套件吃力,重構成本高,穩定性低。

為了能夠將前端模組解耦,透過相關技術調研,最終選擇了無界微前端框架作為物流客服系統解耦支援。為了更好的使用無界微前端框架,我們對其執行機制進行了相關了解,以下是對無界執行機制的一些認識。

基本用法

主應用配置

import WujieVue from 'wujie-vue2';

const { setupApp, preloadApp, bus } = WujieVue;
/*設定快取*/
setupApp({
});
/*預載入*/
preloadApp({
  name: 'vue2'
})
<WujieVue width="100%" height="100%" name="vue2" :url="vue2Url" :sync="true" :alive="true"></WujieVue


具體實踐詳細介紹參考:

http://3.cn/1GyPHN-i/shendeng

https://wujie-micro.github.io/doc/guide/start.html

無界原始碼解析

1 原始碼包目錄結構

packages 包裡包含無界框架核心程式碼wujie-core和對應不同技術棧應用包

examples 使用案例,main-xxx對應該技術棧主應用的使用案例,其他代表子應用的使用案例

2 wujie-vue2元件

該元件預設配置了相關引數,簡化了無界使用時的一些配置項,作為一個全域性元件被主引用使用

這裡使用wujie-vue2示例,其他wujie-react,wujie-vue3大家可自行閱讀,基本作用和wujie-vue2相同都是用來簡化無界配置,方便快速使用

import Vue from "vue";
import { bus, preloadApp, startApp as rawStartApp, destroyApp, setupApp } from "wujie";

const wujieVueOptions = {
  name: "WujieVue",
  props: {
       /*傳入配置引數*/
  },
  data() {
    return {
      startAppQueue: Promise.resolve(),
    };
  },
  mounted() {
    bus.$onAll(this.handleEmit);
    this.execStartApp();
  },
  methods: {
    handleEmit(event, ...args) {
      this.$emit(event, ...args);
    },
    async startApp() {
      try {
        // $props 是vue 2.2版本才有的屬性,所以這裡直接全部寫一遍
        await rawStartApp({
          name: this.name,
          url: this.url,
          el: this.$refs.wujie,
          loading: this.loading,
          alive: this.alive,
          fetch: this.fetch,
          props: this.props,
          attrs: this.attrs,
          replace: this.replace,
          sync: this.sync,
          prefix: this.prefix,
          fiber: this.fiber,
          degrade: this.degrade,
          plugins: this.plugins,
          beforeLoad: this.beforeLoad,
          beforeMount: this.beforeMount,
          afterMount: this.afterMount,
          beforeUnmount: this.beforeUnmount,
          afterUnmount: this.afterUnmount,
          activated: this.activated,
          deactivated: this.deactivated,
          loadError: this.loadError,
        });
      } catch (error) {
        console.log(error);
      }
    },
    execStartApp() {
      this.startAppQueue = this.startAppQueue.then(this.startApp);
    },
    destroy() {
      destroyApp(this.name);
    },
  },
  beforeDestroy() {
    bus.$offAll(this.handleEmit);
  },
  render(c) {
    return c("div", {
      style: {
        width: this.width,
        height: this.height,
      },
      ref: "wujie",
    });
  },
};

const WujieVue = Vue.extend(wujieVueOptions);

WujieVue.setupApp = setupApp;
WujieVue.preloadApp = preloadApp;
WujieVue.bus = bus;
WujieVue.destroyApp = destroyApp;
WujieVue.install = function (Vue) {
  Vue.component("WujieVue", WujieVue);
};
export default WujieVue;


3 入口defineWujieWebComponent和StartApp

首先從入口檔案index看起,defineWujieWebComponent

import { defineWujieWebComponent } from "./shadow";
// 定義webComponent容器
defineWujieWebComponent();

// 定義webComponent  存在shadow.ts 檔案中
export function defineWujieWebComponent() {
  class WujieApp extends HTMLElement {
    connectedCallback(){
      if (this.shadowRoot) return;
      const shadowRoot = this.attachShadow({ mode: "open" });
      const sandbox = getWujieById(this.getAttribute(WUJIE_DATA_ID));
      patchElementEffect(shadowRoot, sandbox.iframe.contentWindow);
      sandbox.shadowRoot = shadowRoot;
    }
    disconnectedCallback() {
      const sandbox = getWujieById(this.getAttribute(WUJIE_DATA_ID));
      sandbox?.unmount();
    }
  }
  customElements?.define("wujie-app", WujieApp);
}


startApp方法

startApp(options) {
  const newSandbox = new WuJie({ name, url, attrs, degradeAttrs, fiber, degrade, plugins, lifecycles });
  const { template, getExternalScripts, getExternalStyleSheets } = await importHTML({
    url,
    html,
    opts: {
      fetch: fetch || window.fetch,
      plugins: newSandbox.plugins,
      loadError: newSandbox.lifecycles.loadError,
      fiber,
    },
  });
  const processedHtml = await processCssLoader(newSandbox, template, getExternalStyleSheets);
  await newSandbox.active({ url, sync, prefix, template: processedHtml, el, props, alive, fetch, replace });
  await newSandbox.start(getExternalScripts);
  return newSandbox.destroy;




4 例項化

4-1, wujie (sandbox.ts)

// wujie
class wujie {
  constructor(options) {
    /** iframeGenerator在 iframe.ts中**/
    this.iframe = iframeGenerator(this, attrs, mainHostPath, appHostPath, appRoutePath);

    if (this.degrade) { // 降級模式
      const { proxyDocument, proxyLocation } = localGenerator(this.iframe, urlElement, mainHostPath, appHostPath);
      this.proxyDocument = proxyDocument;
      this.proxyLocation = proxyLocation;
    } else {           // 非降級模式
      const { proxyWindow, proxyDocument, proxyLocation } = proxyGenerator();
      this.proxy = proxyWindow;
      this.proxyDocument = proxyDocument;
      this.proxyLocation = proxyLocation;
    }
    this.provide.location = this.proxyLocation;
    addSandboxCacheWithWujie(this.id, this);
  }
}


4-2.非降級Proxygenerator

非降級模式window、document、location代理

window代理攔截,修改this指向

export function proxyGenerator(
  iframe: HTMLIFrameElement,
  urlElement: HTMLAnchorElement,
  mainHostPath: string,
  appHostPath: string
): {
  proxyWindow: Window;
  proxyDocument: Object;
  proxyLocation: Object;
} {
  const proxyWindow = new Proxy(iframe.contentWindow, {
    get: (target: Window, p: PropertyKey): any => {
      // location進行劫持
      /*xxx*/
      // 修正this指標指向
      return getTargetValue(target, p);
    },
    set: (target: Window, p: PropertyKey, value: any) => {
      checkProxyFunction(value);
      target[p] = value;
      return true;
    },
    /**其他方法屬性**/
  });

  // proxy document
  const proxyDocument = new Proxy(
    {},
    {
      get: function (_fakeDocument, propKey) {
        const document = window.document;
        const { shadowRoot, proxyLocation } = iframe.contentWindow.__WUJIE;
        const rawCreateElement = iframe.contentWindow.__WUJIE_RAW_DOCUMENT_CREATE_ELEMENT__;
        const rawCreateTextNode = iframe.contentWindow.__WUJIE_RAW_DOCUMENT_CREATE_TEXT_NODE__;
        // need fix
        /* 包括元素建立,元素選擇操作等
         createElement,createTextNode, documentURI,URL,querySelector,querySelectorAll
         documentElement,scrollingElement ,forms,images,links等等
        */
        // from shadowRoot
        if (propKey === "getElementById") {
          return new Proxy(shadowRoot.querySelector, {
            // case document.querySelector.call
            apply(target, ctx, args) {
              if (ctx !== iframe.contentDocument) {
                return ctx[propKey]?.apply(ctx, args);
              }
              return target.call(shadowRoot, `[id="${args[0]}"]`);
            },
          });
        }
      },
    }
  );

  // proxy location
  const proxyLocation = new Proxy(
    {},
    {
      get: function (_fakeLocation, propKey) {
        const location = iframe.contentWindow.location;
        if (
          propKey === "host" || propKey === "hostname" || propKey === "protocol" || propKey === "port" ||
          propKey === "origin"
        ) {
          return urlElement[propKey];
        }
        /** 攔截相關propKey, 返回對應lication內容
        propKey =="href","reload","replace"
        **/
        return getTargetValue(location, propKey);
      },
      set: function (_fakeLocation, propKey, value) {
        // 如果是跳轉連結的話重開一個iframe
        if (propKey === "href") {
          return locationHrefSet(iframe, value, appHostPath);
        }
        iframe.contentWindow.location[propKey] = value;
        return true;
      }
    }
  );
  return { proxyWindow, proxyDocument, proxyLocation };
}



4-3,降級模式localGenerator

export function localGenerator(
){
  // 代理 document
  Object.defineProperties(proxyDocument, {
    createElement: {
      get: () => {
        return function (...args) {
          const element = rawCreateElement.apply(iframe.contentDocument, args);
          patchElementEffect(element, iframe.contentWindow);
          return element;
        };
      },
    },
  });
  // 普通處理
  const {
    modifyLocalProperties,
    modifyProperties,
    ownerProperties,
    shadowProperties,
    shadowMethods,
    documentProperties,
    documentMethods,
  } = documentProxyProperties;
  modifyProperties
    .filter((key) => !modifyLocalProperties.includes(key))
    .concat(ownerProperties, shadowProperties, shadowMethods, documentProperties, documentMethods)
    .forEach((key) => {
      Object.defineProperty(proxyDocument, key, {
        get: () => {
          const value = sandbox.document?.[key];
          return isCallable(value) ? value.bind(sandbox.document) : value;
        },
      });
    });

  // 代理 location
  const proxyLocation = {};
  const location = iframe.contentWindow.location;
  const locationKeys = Object.keys(location);
  const constantKey = ["host", "hostname", "port", "protocol", "port"];
  constantKey.forEach((key) => {
    proxyLocation[key] = urlElement[key];
  });
  Object.defineProperties(proxyLocation, {
    href: {
      get: () => location.href.replace(mainHostPath, appHostPath),
      set: (value) => {
        locationHrefSet(iframe, value, appHostPath);
      },
    },
    reload: {
      get() {
        warn(WUJIE_TIPS_RELOAD_DISABLED);
        return () => null;
      },
    },
  });
  return { proxyDocument, proxyLocation };
}


例項化化主要是建立起js執行時的沙箱iframe, 透過非降級模式下proxy和降級模式下對document,location,window等全域性操作屬性的攔截修改將其和對應的js沙箱操作關聯起來

5 importHTML入口檔案解析

importHtml方法(entry.ts)

export default function importHTML(params: {
  url: string;
  html?: string;
  opts: ImportEntryOpts;
}): Promise<htmlParseResult> {
  /*xxxx*/
  const getHtmlParseResult = (url, html, htmlLoader) =>
    (html
      ? Promise.resolve(html)
      : fetch(url).then( /** 使用fetch Api 載入子應用入口**/
          (response) => response.text(),
          (e) => {
            embedHTMLCache[url] = null;
            loadError?.(url, e);
            return Promise.reject(e);
          }
        )
    ).then((html) => {
      const assetPublicPath = getPublicPath(url);
      const { template, scripts, styles } = processTpl(htmlLoader(html), assetPublicPath);
      return {
        template: template,
        assetPublicPath,
        getExternalScripts: () =>
          getExternalScripts(
            scripts
              .filter((script) => !script.src || !isMatchUrl(script.src, jsExcludes))
              .map((script) => ({ ...script, ignore: script.src && isMatchUrl(script.src, jsIgnores) })),
            fetch,
            loadError,
            fiber
          ),
        getExternalStyleSheets: () =>
          getExternalStyleSheets(
            styles
              .filter((style) => !style.src || !isMatchUrl(style.src, cssExcludes))
              .map((style) => ({ ...style, ignore: style.src && isMatchUrl(style.src, cssIgnores) })),
            fetch,
            loadError
          ),
      };
    });

  if (opts?.plugins.some((plugin) => plugin.htmlLoader)) {
    return getHtmlParseResult(url, html, htmlLoader);
    // 沒有html-loader可以做快取
  } else {
    return embedHTMLCache[url] || (embedHTMLCache[url] = getHtmlParseResult(url, html, htmlLoader));
  }
}


importHTML結構如圖:

注意點: 透過Fetch url載入子應用資源,這裡也是需要子應用支援跨域設定的原因

6 CssLoader和樣式載入最佳化

export async function processCssLoader(
  sandbox: Wujie,
  template: string,
  getExternalStyleSheets: () => StyleResultList
): Promise<string> {
  const curUrl = getCurUrl(sandbox.proxyLocation);
  /** css-loader */
  const composeCssLoader = compose(sandbox.plugins.map((plugin) => plugin.cssLoader));
  const processedCssList: StyleResultList = getExternalStyleSheets().map(({ src, ignore, contentPromise }) => ({
    src,
    ignore,
    contentPromise: contentPromise.then((content) => composeCssLoader(content, src, curUrl)),
  }));
  const embedHTML = await getEmbedHTML(template, processedCssList);
  return sandbox.replace ? sandbox.replace(embedHTML) : embedHTML;
}


7 子應用active

active方法主要用於做 子應用啟用, 同步路由,動態修改iframe的fetch, 準備shadow, 準備子應用注入

7-1, active方法(sandbox.ts)

public async active(options){
    /**  options的檢查  **/
    // 處理子應用自定義fetch
    // TODO fetch檢驗合法性
    const iframeWindow = this.iframe.contentWindow;
    iframeWindow.fetch = iframeFetch;
    this.fetch = iframeFetch;
   

    // 處理子應用路由同步
    if (this.execFlag && this.alive) {
      // 當保活模式下子應用重新啟用時,只需要將子應用路徑同步回主應用
      syncUrlToWindow(iframeWindow);
    } else {
      // 先將url同步回iframe,然後再同步回瀏覽器url
      syncUrlToIframe(iframeWindow);
      syncUrlToWindow(iframeWindow);
    }

    // inject template
    this.template = template ?? this.template;

    /* 降級處理 */
    if (this.degrade) {
      return;
    }

    if (this.shadowRoot) {
      this.el = renderElementToContainer(this.shadowRoot.host, el);
      if (this.alive) return;
    } else {
      // 預執行無容器,暫時插入iframe內部觸發Web Component的connect
      // rawDocumentQuerySelector.call(iframeWindow.document, "body") 相當於Document.prototype.querySelector('body')
      const iframeBody = rawDocumentQuerySelector.call(iframeWindow.document, "body") as HTMLElement;
        
      this.el = renderElementToContainer(createWujieWebComponent(this.id), el ?? iframeBody);
    }

    await renderTemplateToShadowRoot(this.shadowRoot, iframeWindow, this.template);
    this.patchCssRules();

    // inject shadowRoot to app
    this.provide.shadowRoot = this.shadowRoot;
  }


7-2,createWujieWebComponent, renderElementToContainer, renderTemplateToShadowRoot

// createWujieWebComponent
export function createWujieWebComponent(id: string): HTMLElement {
  const contentElement = window.document.createElement("wujie-app");
  contentElement.setAttribute(WUJIE_DATA_ID, id);
  contentElement.classList.add(WUJIE_IFRAME_CLASS);
  return contentElement;
}

/**
 * 將準備好的內容插入容器
 */
export function renderElementToContainer(
  element: Element | ChildNode,
  selectorOrElement: string | HTMLElement
): HTMLElement {
  const container = getContainer(selectorOrElement);
  if (container && !container.contains(element)) {
    // 有 loading 無需清理,已經清理過了
    if (!container.querySelector(`div[${LOADING_DATA_FLAG}]`)) {
      // 清除內容
      clearChild(container);
    }
    // 插入元素
    if (element) {
      //  rawElementAppendChild = HTMLElement.prototype.appendChild;
      rawElementAppendChild.call(container, element);
    }
  }
  return container;
}
/**
 * 將template渲染到shadowRoot
 */
export async function renderTemplateToShadowRoot(
  shadowRoot: ShadowRoot,
  iframeWindow: Window,
  template: string
): Promise<void> {
  const html = renderTemplateToHtml(iframeWindow, template);
  // 處理 css-before-loader 和 css-after-loader
  const processedHtml = await processCssLoaderForTemplate(iframeWindow.__WUJIE, html);
  // change ownerDocument
  shadowRoot.appendChild(processedHtml);
  const shade = document.createElement("div");
  shade.setAttribute("style", WUJIE_SHADE_STYLE);
  processedHtml.insertBefore(shade, processedHtml.firstChild);
  shadowRoot.head = shadowRoot.querySelector("head");
  shadowRoot.body = shadowRoot.querySelector("body");

  // 修復 html parentNode
  Object.defineProperty(shadowRoot.firstChild, "parentNode", {
    enumerable: true,
    configurable: true,
    get: () => iframeWindow.document,
  });

  patchRenderEffect(shadowRoot, iframeWindow.__WUJIE.id, false);
}
/**
 * 將template渲染成html元素
 */
function renderTemplateToHtml(iframeWindow: Window, template: string): HTMLHtmlElement {
  const sandbox = iframeWindow.__WUJIE;
  const { head, body, alive, execFlag } = sandbox;
  const document = iframeWindow.document;
  let html = document.createElement("html");
  html.innerHTML = template;
  // 元件多次渲染,head和body必須一直使用同一個來應對被快取的場景
  if (!alive && execFlag) {
    html = replaceHeadAndBody(html, head, body);
  } else {
    sandbox.head = html.querySelector("head");
    sandbox.body = html.querySelector("body");
  }
  const ElementIterator = document.createTreeWalker(html, NodeFilter.SHOW_ELEMENT, null, false);
  let nextElement = ElementIterator.currentNode as HTMLElement;
  while (nextElement) {
    patchElementEffect(nextElement, iframeWindow);
    const relativeAttr = relativeElementTagAttrMap[nextElement.tagName];
    const url = nextElement[relativeAttr];
    if (relativeAttr) nextElement.setAttribute(relativeAttr, getAbsolutePath(url, nextElement.baseURI || ""));
    nextElement = ElementIterator.nextNode() as HTMLElement;
  }
  if (!html.querySelector("head")) {
    const head = document.createElement("head");
    html.appendChild(head);
  }
  if (!html.querySelector("body")) {
    const body = document.createElement("body");
    html.appendChild(body);
  }
  return html;
}
/*
// 儲存原型方法
// 子應用的Document.prototype已經被改寫了
export const rawElementAppendChild = HTMLElement.prototype.appendChild;
export const rawElementRemoveChild = HTMLElement.prototype.removeChild;
export const rawHeadInsertBefore = HTMLHeadElement.prototype.insertBefore;
export const rawBodyInsertBefore = HTMLBodyElement.prototype.insertBefore;
export const rawAddEventListener = Node.prototype.addEventListener;
export const rawRemoveEventListener = Node.prototype.removeEventListener;
export const rawWindowAddEventListener = window.addEventListener;
export const rawWindowRemoveEventListener = window.removeEventListener;
export const rawAppendChild = Node.prototype.appendChild;
export const rawDocumentQuerySelector = window.__POWERED_BY_WUJIE__
  ? window.__WUJIE_RAW_DOCUMENT_QUERY_SELECTOR__
  : Document.prototype.querySelector;
*/



8 子應用啟動執行start

start 開始執行子應用,執行js,執行無界js外掛列表

public async start(getExternalScripts: () => ScriptResultList): Promise<void> {
    this.execFlag = true;
    // 執行指令碼
    const scriptResultList = await getExternalScripts();
    const iframeWindow = this.iframe.contentWindow;
    // 標誌位,執行程式碼前設定
    iframeWindow.__POWERED_BY_WUJIE__ = true;
    // 使用者自定義程式碼前 
    const beforeScriptResultList: ScriptObjectLoader[] = getPresetLoaders("jsBeforeLoaders", this.plugins);
    // 使用者自定義程式碼後
    const afterScriptResultList: ScriptObjectLoader[] = getPresetLoaders("jsAfterLoaders", this.plugins);
    // 同步程式碼
    const syncScriptResultList: ScriptResultList = [];
    // async程式碼無需保證順序,所以不用放入執行佇列
    const asyncScriptResultList: ScriptResultList = [];
    // defer程式碼需要保證順序並且DOMContentLoaded前完成,這裡統一放置同步指令碼後執行
    const deferScriptResultList: ScriptResultList = [];
    scriptResultList.forEach((scriptResult) => {
      if (scriptResult.defer) deferScriptResultList.push(scriptResult);
      else if (scriptResult.async) asyncScriptResultList.push(scriptResult);
      else syncScriptResultList.push(scriptResult);
    });

    // 插入程式碼前
    beforeScriptResultList.forEach((beforeScriptResult) => {
      this.execQueue.push(() =>
        this.fiber
          ? requestIdleCallback(() => insertScriptToIframe(beforeScriptResult, iframeWindow))
          : insertScriptToIframe(beforeScriptResult, iframeWindow)
      );
    });
    // 同步程式碼
    syncScriptResultList.concat(deferScriptResultList).forEach((scriptResult) => {
      /**xxxxx**/
    });

    // 非同步程式碼
    asyncScriptResultList.forEach((scriptResult) => {
      scriptResult.contentPromise.then((content) => {
        this.fiber
          ? requestIdleCallback(() => insertScriptToIframe({ ...scriptResult, content }, iframeWindow))
          : insertScriptToIframe({ ...scriptResult, content }, iframeWindow);
      });
    });

    //框架主動呼叫mount方法
    this.execQueue.push(this.fiber ? () => requestIdleCallback(() => this.mount()) : () => this.mount());

    //觸發 DOMContentLoaded 事件
    const domContentLoadedTrigger = () => {
      eventTrigger(iframeWindow.document, "DOMContentLoaded");
      eventTrigger(iframeWindow, "DOMContentLoaded");
      this.execQueue.shift()?.();
    };
    this.execQueue.push(this.fiber ? () => requestIdleCallback(domContentLoadedTrigger) : domContentLoadedTrigger);

    // 插入程式碼後
    afterScriptResultList.forEach((afterScriptResult) => {
      /**xxxxx**/
    });

    //觸發 loaded 事件
    const domLoadedTrigger = () => {
      eventTrigger(iframeWindow.document, "readystatechange");
      eventTrigger(iframeWindow, "load");
      this.execQueue.shift()?.();
    };
    this.execQueue.push(this.fiber ? () => requestIdleCallback(domLoadedTrigger) : domLoadedTrigger);
    // 由於沒有辦法準確定位是哪個程式碼做了mount,保活、重建模式提前關閉loading
    if (this.alive || !isFunction(this.iframe.contentWindow.__WUJIE_UNMOUNT)) removeLoading(this.el);
    this.execQueue.shift()();

    // 所有的execQueue佇列執行完畢,start才算結束,保證序列的執行子應用
    return new Promise((resolve) => {
      this.execQueue.push(() => {
        resolve();
        this.execQueue.shift()?.();
      });
    });
  }


// getExternalScripts
export function getExternalScripts(
  scripts: ScriptObject[],
  fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response> = defaultFetch,
  loadError: loadErrorHandler,
  fiber: boolean
): ScriptResultList {
  // module should be requested in iframe
  return scripts.map((script) => {
    const { src, async, defer, module, ignore } = script;
    let contentPromise = null;
    // async
    if ((async || defer) && src && !module) {
      contentPromise = new Promise((resolve, reject) =>
        fiber
          ? requestIdleCallback(() => fetchAssets(src, scriptCache, fetch, false, loadError).then(resolve, reject))
          : fetchAssets(src, scriptCache, fetch, false, loadError).then(resolve, reject)
      );
      // module || ignore
    } else if ((module && src) || ignore) {
      contentPromise = Promise.resolve("");
      // inline
    } else if (!src) {
      contentPromise = Promise.resolve(script.content);
      // outline
    } else {
      contentPromise = fetchAssets(src, scriptCache, fetch, false, loadError);
    }
    return { ...script, contentPromise };
  });
}

// 載入assets資源 
// 如果存在快取則從快取中獲取
const fetchAssets = (
  src: string,
  cache: Object,
  fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>,
  cssFlag?: boolean,
  loadError?: loadErrorHandler
) =>
  cache[src] ||
  (cache[src] = fetch(src)
    .then((response) => {
     /**status > 400按error處理**/
      return response.text();
    })
 }));

// insertScriptToIframe
export function insertScriptToIframe(
  scriptResult: ScriptObject | ScriptObjectLoader,
  iframeWindow: Window,
  rawElement?: HTMLScriptElement
) {
  const { src, module, content, crossorigin, crossoriginType, async, callback, onload } =
    scriptResult as ScriptObjectLoader;
  const scriptElement = iframeWindow.document.createElement("script");
  const nextScriptElement = iframeWindow.document.createElement("script");
  const { replace, plugins, proxyLocation } = iframeWindow.__WUJIE;
  const jsLoader = getJsLoader({ plugins, replace });
  let code = jsLoader(content, src, getCurUrl(proxyLocation));

  // 內聯指令碼處理
  if (content) {
    // patch location
    if (!iframeWindow.__WUJIE.degrade && !module) {
      code = `(function(window, self, global, location) {
      ${code}
}).bind(window.__WUJIE.proxy)(
  window.__WUJIE.proxy,
  window.__WUJIE.proxy,
  window.__WUJIE.proxy,
  window.__WUJIE.proxyLocation,
);`;
    }
  } else {
    // 外聯自動觸發onload
    onload && (scriptElement.onload = onload as (this: GlobalEventHandlers, ev: Event) => any);
    src && scriptElement.setAttribute("src", src);
    crossorigin && scriptElement.setAttribute("crossorigin", crossoriginType);
  }
  // esm 模組載入
  module && scriptElement.setAttribute("type", "module");
  scriptElement.textContent = code || "";
  // 執行script佇列檢測
  nextScriptElement.textContent =
    "if(window.__WUJIE.execQueue && window.__WUJIE.execQueue.length){ window.__WUJIE.execQueue.shift()()}";

  const container = rawDocumentQuerySelector.call(iframeWindow.document, "head");
  if (/^<!DOCTYPE html/i.test(code)) {
    error(WUJIE_TIPS_SCRIPT_ERROR_REQUESTED, scriptResult);
    return !async && container.appendChild(nextScriptElement);
  }
  container.appendChild(scriptElement);

  // 呼叫回撥
  callback?.(iframeWindow);
  // 執行 hooks
  execHooks(plugins, "appendOrInsertElementHook", scriptElement, iframeWindow, rawElement);
  // 外聯轉內聯呼叫手動觸發onload
  content && onload?.();
  // async指令碼不在執行佇列,無需next操作
  !async && container.appendChild(nextScriptElement);
}



9 子應用銷燬

/** 銷燬子應用 */
  public destroy() {
    this.bus.$clear();
    // thi.xxx = null;
    // 清除 dom
    if (this.el) {
      clearChild(this.el);
      this.el = null;
    }
    // 清除 iframe 沙箱
    if (this.iframe) {
      this.iframe.parentNode?.removeChild(this.iframe);
    }
    // 刪除快取
    deleteWujieById(this.id);
  }


主應用,無界,子應用之間的關係

主應用建立自定義元素和建立iframe元素

無界將子應用解析後的html,css加入到自定義元素,進行元素和樣式隔離

同時建立iframe代理,將iframe和自定義元素shadowDom進行關聯,

將子應用中的js放入iframe執行,iframe中js執行的結果被代理到修改shadowDom結構和資料

作者:京東物流 張燕燕、劉海鼎

來源:京東雲開發者社群 自猿其說Tech 轉載請註明來源

相關文章