Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

cookies - How to import a javascript library CDN into a javascript file and use that same library in that file?

This might be a little confusing - I'm trying to retrieve the value of a cookie from inside a js file and to do this im using the js-cookie library over a CDN create from the JS file. However Cookies is undefined when i try to access the library.

I'm wondering what the problem is and what my best option is to do this?

var jQueryScript = document.createElement("script");
jQueryScript.setAttribute(
  "src",
  "https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js"
);
jQueryScript.setAttribute("type", "module");
document.head.appendChild(jQueryScript);

// Cookies.get is not defined.
var cookieval = Cookies.get("shopOrigin");
console.log(cookieval);

Any help would be much appeciated, it is most likely something simple i am missing. Thanks

question from:https://stackoverflow.com/questions/65916379/how-to-import-a-javascript-library-cdn-into-a-javascript-file-and-use-that-same

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

1 Answer

0 votes
by (71.8m points)
    const loadScript = url => new Promise((resolve, reject) => {
      const node = document.createElement('script')
      node.setAttribute('src', url)
      node.onload = resolve
      node.reject = reject 
      document.body.appendChild(node)
    })

    loadScript('//cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js')
      .then(() => {
        // do your job here
        console.log(window.Cookies)
      })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...