[Vuejs]-How to import js file from cdn?

0👍

To import the JS file from CDN and use in vue.js component, you can use mounted lifecycle and there you need to append your script into DOM.

Then it will be available into your window global variable.

Working code example:

mounted () {
  let pdfJS = document.createElement('script')
  pdfJS.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.min.js')
  document.head.appendChild(pdfJS)
  // for checking whether it's loaded in windows are not, I am calling the below function.
  this.checkPDFJSLib()
},
methods: {
  checkPDFJSLib() {
    console.log(window.pdfjsLib)
  }
}

0👍

You can normally include it in your index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.min.js"></script>

Alternatively, you can use an npm library e.g vue-pdf

install it into your modules

npm install --save vue-pdf

and use it

import pdf from 'vue-pdf'

Leave a comment