2

Is there a way to selectively register a stimulus controller so it doesn't get registered on every page in Rails 7.

I have a stimulus controller stripe_controller.js that imports stripe-js:


    import { loadStripe } from "@stripe/stripe-js"

and this is causing stripe to generate an iFrame on every page of my site even when the controller is not connected.

My app/javascript/controllers/index.js is loading my controller:


    import { application } from "./application"

    import StripeController from "./stripe_controller"
    application.register("stripe", StripeController)

Is there a way to dynamically register instead of including it in the index.js file?

2
  • its recommended to load it on every page to keep an eye on shifty behavior. but, maybe this will do it: github.com/stripe/… Commented Aug 19, 2023 at 2:51
  • 1
    Alex - your suggestion also works, thanks! To make this work with importmaps i had to change my pin from pin "@stripe/stripe-js", to: "https://ga.jspm.io/npm:@stripe/[email protected]/dist/stripe.esm.js" to pin "@stripe/stripe-js/pure", to: "https://ga.jspm.io/npm:@stripe/[email protected]/dist/stripe.esm.js". Commented Aug 26, 2023 at 2:33

1 Answer 1

3

I eventually found a solution in the ImportMap Documentation :| https://github.com/rails/importmap-rails#selectively-importing-modules.

Basically, you can move the register code from app/javascript/controllers/index.js to a new js file such as app/javascript/register.js.

import { application } from "./controllers/application"

import StripeController from "./controllers/stripe_controller"
application.register("stripe", StripeController)

Then you need to pin it to importmap.rb

pin "register"

Then you need to yield it into the the header, so if you don't already have something like <%= yield(:head) %> in your application.html.erb layout then add it. Now you can yield the register script on the ERB pages you need it like so:

<%= content_for :head do %>
    <%= javascript_import_module_tag "register %>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

This solution works but Alex's suggestion to use stripe-js/pure is the way to go for a Stripe integration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.