0

I dynamically added StripeCheckout script in the DOM like:

var script = document.createElement(`script`);
script.src = `https://checkout.stripe.com/checkout.js`;
document.getElementsByTagName('head')[0].appendChild(script);

When I do console.log(window) I get :

enter image description here

But when I do console.log(window.StripeCheckout) I freaking get an undefined.

Why?

P.S. window.StripeCheckout is present when I accessed it directly from the dev console.

enter image description here

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
jofftiquez
  • 7,548
  • 10
  • 67
  • 121

2 Answers2

4

Why?

Because it takes time to load and execute the script. When you log window, by the time you expand the object, the script has loaded and executed. Same for when you run window.StripeCheckout in the developer console.

When you hover over that little [i] in the console it will also tell you that the "content" of the object was just evaluated when you expanded that line.

Additionally, because JavaScript runs to completion, it is guaranteed that console.log(window.StripeCheckout) is executed before the script is evaluated. So the property cannot exist at that moment, even if the script was available immediately.


If you want to know when the script loaded have a look at

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Wow I did not know that. Thanks. I wrapped my code with `window.addEventListener('load', fn)` and it worked. – jofftiquez Sep 26 '17 at 05:01
3

Try this:

function loadScript(url, callback){

var script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState){  //IE
    script.onreadystatechange = function(){
        if (script.readyState == "loaded" ||
                script.readyState == "complete"){
            script.onreadystatechange = null;
            callback();
        }
    };
} else {  //Others
    script.onload = function(){
        callback();
    };
}

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://checkout.stripe.com/checkout.js", function(){
  console.log(window.StripeCheckout)
});
santho
  • 366
  • 2
  • 16
  • Thanks @santho but I prefer the answer by Felix, it explained the problem well which leads me to the right approach. – jofftiquez Sep 26 '17 at 05:02