Search code examples
angularserver-side-rendering

Importing JS module on client-side with SSR


I have my angular 18 application running with SSR.

I have the following import which fails on page load as the igv.js file contains client-side objects like window, etc:

import * as igv from 'igv';

I need to dynamically import the javascript file on the client-side so that it doesn't fail with the SSR.

I tried the code below but am getting the error message TypeError: igv.createBrowser is not a function,

if (isPlatformBrowser(this.platformId)){
  const promise = import("/Users/Projects/angular-project/igv.js");
  promise.then(igv=> {
    try {
      this.browser = igv.createBrowser(this.igvDiv.nativeElement, this.options);
    } catch (e) {
      console.log(e);
    }

  });
}

Any idea how to dynamically load the igv module on client-side?


Solution

  • What happens is that ngAfterViewInit Lifecycle Hook: Ensures the dynamic import and createBrowser call happen after the view initialization to access the DOM element (this.igvDiv.nativeElement).

    import { Component, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    @Component({
      selector: 'app-your-component',
      templateUrl: './your-component.component.html',
      styleUrls: ['./your-component.component.css']
    })
    export class YourComponent {
    
      browser: any;
      options: any = { /* your options here */ };
    
      constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
    
      ngAfterViewInit() {
        if (isPlatformBrowser(this.platformId)) {
          import('/Users/Projects/angular-project/igv.js').then(igvModule => {
            const igv = igvModule.default;
            if (igv && typeof igv.createBrowser === 'function') {
              this.browser = igv.createBrowser(this.igvDiv.nativeElement, this.options);
            } else {
              console.error('igv.createBrowser is not a function');
            }
          }).catch(error => {
            console.error('Error loading igv module:', error);
          });
        }
      }
    }