What to do if you must add JavaScript in an AMP site?

Before I became an AMP fangirl, I was afraid of trying it out because I thought, “What if I need to include custom JavaScript functionality and can’t do it because AMP doesn’t allow it? That means I’d have to start the site all over!”

I was wrong. If you need to add custom JS in your AMP site, you have three options:

  1. Code a JavaScript snippet and include it in your AMP page via [amp-iframe](https://amp.dev/documentation/components/amp-iframe)
  2. Add the custom JS in the page. That will invalidate the page, BUT your only penalty will be that it won’t be indexed in the AMP cache. All other features (search engine caching, AMP components functionality) will work
  3. Use [amp-script](https://amp.dev/documentation/components/amp-script/). Be wary that ti is much different than ordinary JS with restrictions like size and actions.

Before you add JS, ask yourself these questions:

  • Do I really need the extra code?
  • Is this code going to my make visitor’s browsing experience better?
  • Is this going to slow down my site?
  • Is the lack of this functionality going to hurt my visitors?

And try to implement what you need using AMP actions and events and amp-bind instead of JS.

When I was coding an AMP truck selling website, one of the requirements was a financing payment calculator in their product pages. This is standard since a lot of owner operators can’t afford the 30k - 90k price tag for buying a truck, so they usually finance it. That meant the calculator was a must. I put the calculator on a separate page and then include it in the page via amp-iframe. The page was valid AMP and the functionality was there.

For e-commerce sites, the pages that need the most custom JS are probably the user generated dynamic ones that doesn’t need to be indexed - like the cart pages! So simply code with the JS and AMP will just exclude it from the AMP cache. You won’t lose anything since the content of the cart is dynamically generated.