Load <script> on button click

Hey guys,

Any ideas how to load an external script with a button click trigger?
I am integrating Stripe on my app, but loading the script by default (inside the head element or on page load) significantly increases my page loading times… So I am looking for a way to load the script only when the user initiates a checkout and Stripe is needed.


It should be noted that Stripe advises keeping the script active on all pages for security to be optimal. And their base script is supposed to be lightweight, are you sure it is the package responsible for your loading times ?

1 Like

When I open my app’s page, it remains blank for 4-5 seconds while Chrome indicates on that little window (bottom left) that it is waiting for js.stripe.com

I am using this script:
<script src="https://js.stripe.com/v3/"></script>

and the Stripe NPM Package

Do you use React? Let me give you an example of how I load and initialize the google analytics and you might think to do something similar. In your app JS (above the router), wait for everything to be up… 1 or 2 or 3 or 5 sec and then pull and initialize your Stripe

componentDidMount () {
   setTimeout(() => {
        .then(ReactGA => {
          ReactGA.set({ page: window.location.pathname })

          history.listen((location, action) => {
            ReactGA.set({ page: location.pathname })
    }, 1000)

1 Like

Thanks for the suggestion! I am Blaze (not React), but could try to postpone the script loading somehow…

You could just make it an async script:

<script async src="https://js.stripe.com/v3/"></script>

Then the browser won’t have to wait for it to load before rendering

1 Like

I see the library is only 32kb so you are definitely not waiting on that. On the connection to Stripe as coagmano says, async would help to execute the script after the page is (down)loaded but still while it is painting. If you need to delay further and avail of it as a global object (as a script in the HTML head), you could run something like this, anywhere where you are “close” to facing Stripe e.g when you press a check out button (example for font awesome):

(function () {
      var css = document.createElement('link')
      css.href = 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'
      css.rel = 'stylesheet'
      css.type = 'text/css'
1 Like