'Does AlpineJS have any special way of dynamically loading external JS?

Sometimes, I want to load JS from an external source, but only when it's absolutely necessary. Typically, this is done by creating a <script> element with document.createElement('script'), setting the src, and then appending this to the <head>.

However, I'm curious if AlpineJS has a means of doing this—perhaps with <template> or something—without the browser attempting to load the external JS file until I've told it to.

Is this possible?



Solution 1:[1]

There is no special handling for this in alpineJs.

You could:

  1. Create a property which defines if the script tag should be loaded or not.

  2. Create a method which creates a <script> tag and appends it to the <head> element.

  3. Add a $watcher on the property you created in the first step where you call the method you created in the second step whenever the value of the property fits your needs.

That should do the job.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 demhadesigns