Can't access 3rd party JS in Stimulus controller with Turbo Drive on

I’ve been trying to use PDF.js with a Stimulus controller and have only been able to make it work by disabling Turbo Drive or by forcing full page reloads - ideally I would have working with Turbo Drive on.

I currently have a partial that loads the external PDF.js script in the page’s <head> like so:

<% content_for :external_scripts do %>
  <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<% end %>

I then have a pdfjs_controller.js Stimulus controller that accesses the PDF.js library that the external script puts in the window like so:

  initialize() {
    this.pdfjsLib = window["pdfjs-dist/build/pdf"];
   ...
  }

This works fine when Turbo Drive is off and the page reloads fully. However, if I have Turbo Drive turned on and navigate to this page, window["pdfjs-dist/build/pdf"] is undefined in the Stimulus controller. This is despite the fact I can see the external script has been added to the <head>.

I have tried wrapping the code where we try to access the library in the window in a turbo:load event listener but this didn’t work either.

To make this work without explicitly turning Turbo Drive off I have had to use <meta name="turbo-visit-control" content="reload"> in the <head> but i’d love to get this working with Turbo Drive on.

We use importmaps to load our JS and i’ve tried importing the library that way, rather than via an external script. Having “pinned” the library i’ve tried adding both import * as pdfjsLib from "pdfjs-dist"; and import "pdf-dist;" in the Stimulus controller but they both result in errors where root is undefined in the source code:

(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define("pdfjs-dist/build/pdf", [], factory);
	else if(typeof exports === 'object')
		exports["pdfjs-dist/build/pdf"] = factory();
	else
		root["pdfjs-dist/build/pdf"] = factory();
})(this, () => {
return 

If anyone has any suggestions as to how to get this working with Turbo Drive please let me know.

For what’s it worth, we opted for this approach Turbo Handbook

The library in question isn’t exported as an ESM which is why I was unable to import it.

Perhaps look at something like: