user7776690
user7776690

Reputation:

Javascript ES6 onclick load module...can it be done?

I have created a few es6 modules:

module1.js
module2.js

These modules will load content into a div with id="root"

<div id="root"></div>

document.getElementById('root').innerHTML = (results);

My question is ...

Is is possible to load modules from as onclick event for example:

<li onclick="loadModule('module1')">Load Module 1</li> //load module1.js
<li onclick="loadModule('module2')">Load Module 2</li> //load module2.js

If so, how can I do this?

Upvotes: 2

Views: 1971

Answers (2)

sobhuxa
sobhuxa

Reputation: 11

This is the best solution i found online, The previous answer adds the scripts to the inner html of the page and renders it useless (i cant click on anything)

const myModule = './myModule.js';
import(myModule)
   .then(x => x.someMethod());

Credits to @leonardobrunolima https://medium.com/@leonardobrunolima/javascript-tips-dynamically-importing-es-modules-with-import-f0093dbba8e1

Upvotes: 1

Mμ.
Mμ.

Reputation: 8542

In the following case I am using libraries that you can get through http and then append the html with a script that points to that library you asked to be required. If the module is local, then you just use the filepath of those modules. I assume that those modules are transpiled into some sort of built folder along with the html, so you can access if from there.

function loadModule(module) {
  var script = {
    'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
    'knockout': 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js'
  }[module];
  document.body.innerHTML += `<script src=${script} type='text/javascript'><\/script>`;
  console.log(module + ' module loaded');
}
<button onclick="loadModule('jquery')">Load jquery </button>
<button onclick="loadModule('knockout')">Load knockout.js </button>

Upvotes: 0

Related Questions