Is it possible to lazy load braintree.js on a web page?
See original GitHub issueI want to only load braintree.js
when it is needed, not on page load. I have tried using jQuery’s $.getScript
like so:
$.getScript('https://js.braintreegateway.com/v2/braintree.js')
.done(function () {
client = new braintree.api.Client({
clientToken: config.clientToken
});
});
However, loading it this way does not propagate the braintree
object onto window
, so braintree
does not resolve. I read the documentation and came across this statement:
If you include braintree.js in a
<script>
tag, thebraintree
object will be available on the global namespace.
As such, I have tried dynamically creating a script element and adding it to the page, like so:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://js.braintreegateway.com/v2/braintree.js';
document.getElementsByTagName('head')[0].appendChild(script);
// I've also tried: document.body.appendChild(script)
The script is fetched and shows up in my loaded scripts, but the braintree
object still is not added to window
.
Is there any way to lazy load braintree.js? I really do not want to load a 50kb (gzipped) script unless the user actually needs it, which isn’t always the case.
Issue Analytics
- State:
- Created 8 years ago
- Comments:8
Top GitHub Comments
I tested the first snippet you posted with jQuery 1.11.2 and it worked for me;
window.braintree
was defined after running that. What version of jQuery are you using?The second snippet you posted should also work so long as you wait for the script to load before you start using
braintree
:Hope this helps!
Let us know if you have more problems!