CENT1PEDE CENT1PEDE - 23 days ago 13
Javascript Question

Object inside window is present but undefined when invoked

I dynamically added

script in the DOM like:

var script = document.createElement(`script`);
script.src = `https://checkout.stripe.com/checkout.js`;

When I do
I get :

enter image description here

But when I do
I freaking get an


is present when I accessed it directly from the dev console.

enter image description here

Answer Source


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