Search code examples
javascriptecmascript-5

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


Solution

  • 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 :)