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

Categories

0 votes
650 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...