简体   繁体   中英

Shareable component in ES5

modern javascript framework like Vue, React and angular has support to create shareable component across page/module in web app. How the best way I achieve this using HTML + ES5? Any library or framework? I am using legacy code that doesn't support ES6

You can create the HTML elements from JS and either bring a .css file with it for styling purposes or style it with JS. And then you would just import it to your HTML like so:

<script src="yourcomponent/index.js"></script>

You can also use a cdn to deploy your component.

Example index.js in your component:

function createRoot() {
  const rootElement = document.createElement("div");

  document.body.appendChild(rootElement);

  return rootElement;
}

function createComponent(root = createRoot(), elementType, className) {
   const componentWrapper = document.createElement(elementType);
   componentWrapper.setAttribute("class", className);

   return componentWrapper;
}


// usage

// you can pass root or not
const component = createComponent(document.getElementById("root"), "div", "my-component-wrapper");

You can then append extra DOM nodes to it or apply functionality. All of which wil be able to be carried over with your script.

Hope this serves as inspiration:)

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.

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