How do I dynamically import scripts?

My Tiptap plugin needs to load a ton of scripts. I now allow users to dynamically choose which functionalities they want to use – however I still load all the libraries. I’m looking to optimize that by loading only the requested libraries.

I looked around MDN and peered into @keith’s Loaderr plugin. I got it to work with this code

const s = document.createDocumentFragment();

const e = document.createElement("script");

e.type = 'module';
e.innerText = `import { Editor } from "";window.tiptapEditor = Editor;`;

const createdScript = document.head.appendChild(s)

On the browser’s console, I can see window.tiptapEditor so that works.

However, I can’t grab on to that inside the update function in the plugin. If I try to console.log it, it shows up as undefined.

I’m guessing it’s a timing error – the script is not yet loaded when I call it right afterwards. I tried adding a e.onload but that function never gets called.

Any ideas?

Give this a :eyes:

@rico.trevisan, this isn’t a very good example, sorry to say. The “core” part (the part required by EVERY instance, regardless of options), should be loaded in instance. Once you do that, if you then have trouble loading options (which you would load in update, as that is where you can SEE the option fields), add some context here.

(Aside: I see little value in optimizing in this way. Bubble loads all sorts of crap that the page in question does not need. The fact that it does that is NOT related to how “slow” Bubble seems. Bubble seems slow because on shared “servers” [which are not even real servers], we are just waiting around for Bubble to respond. Writing tight code contributes nothing to improving this.)

1 Like