Why module import not working inside a function?

I want to import a three js loader module inside a function as follows

function loadIFC(){
 import { IFCLoader } from './static/javascript/three.js-dev/examples/jsm/loaders/IFCLoader.js';
 const ifcLoader = new IFCLoader();
    ifcLoader.ifcManager.setWasmPath( '../static/javascript/three.js-dev/examples/jsm/loaders/ifc/' );
    ifcLoader.load( '../static/utils/example.ifc', function ( model ) {
            console.log("model loaded succussfully")
    });
}

It gives me the following error

Uncaught SyntaxError: Cannot use import statement outside a module

How can I import an IFCloader.js inside a function without any error ?

Why would you want to do that?

My goal is to load an IFC module on button click. I don`t want to render any module. I just want to access the IFC properties on button click. So the above mentioned function “loadIFC()” should be called on button click.

Your code won’t work like this but you can import modules dynamically in JavaScript like this:

import('/modules/my-module.js')
  .then((module) => {
    // Do something with the module.
  });

Or like this using async/await syntax:

let module = await import('/modules/my-module.js');

Have look at this page for more information.

3 Likes

What should happen if you click the button 1000 times? Do you expect to load the IFC module 1000 times?

@dubois Yes it is. The requirement is to select(file-input) the IFC file in the client pc, then load the IFC file and display the IFCSENSOR properties on webpage on button click.

Thank you very much. First option worked well.

1 Like

I think you want to load the ifc file 1000 times in the case above, not the library module that loads the ifc files. @Benny could you please explain what would happen here? Would the module be cached, would there be additional requests?

From my experience the browser should cache the requested files. So when you click on the button the first time the files will be requested asynchronous and the callback will be executed. The following button clicks won’t download the files again, instead the cached files will be used and the callback will still be executed as expected. This behaviour can be observed in the developer tools network tab.

1 Like

@Benny I just want to ask something that doesn’t related to the original question, but related to ThreeJS.

Is it possible to run the above ThreeJS implementation on server side rather than client side using nodejs ?