Dynamically load external javascript into component

I am trying to load external library (Javascript) into Angular2 component (TypeScript).

Example: https://github.com/fengyuanchen/cropperjs

My approach:

index.html

<head>
   <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.css" rel="stylesheet">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.js"></script>
</head>

      

myCropper.js

window.addEventListener('DOMContentLoaded', function () {
 var image = document.querySelector('#image');
 var cropper = new Cropper(image, {
    viewMode: 3,
    dragMode: 'move',
    autoCropArea: 1,
    restore: false,
    modal: false,
    guides: false,
    highlight: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false,
  });
 });

      

photo.component.ts

@Component({
selector: 'photo-crop',
template: `
    <div class="row">
      <img id="image" src="http://img01.ibnlive.in/ibnlive/uploads/875x584/jpg/2015/09/new-google-logo-010915.png" class="img-responsive"/>
    <div class="row">
    `,
styles: []
})
export class PhotoComponent {

public ngOnInit() {
    this.loadScript('src/assets/js/myCropper.js');           
    });
}

public loadScript(url) {
    console.log('preparing to load...')
    let node = document.createElement('script');
    node.src = url;
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);
 }
}

      

Problem: Image loads without scaling / cropping effect. I checked the page and saw that the script was added correctly. I have refreshed the page with no luck. I didn't have any error. Angular2 doesn't seem to activate the script.

I also tried a workaround: by putting the script in index.html directly (this workaround is returning when the page hasn't loaded yet)

<head>
  ...
  <script src="src/assets/js/myCropper.js"></script>
</head>

      

Photo is loaded with no zoom / crop effect on startup. But after refreshing the page, the zoom / crop effect is activated. It is not a good practice to keep all scripts in index.html, but at least the script works after the update.

Any suggestion is appreciated.

+3


source to share





All Articles