Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vue.js - How to import js file from cdn?

How do we import js file from cdn? I am building a custom component (a wrapper component) to view the pdf files. and for this I need to use pdf.js file from cdn and I am unable to import the file?

following does not work

import "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.min.js";
question from:https://stackoverflow.com/questions/65880557/how-to-import-js-file-from-cdn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...