I'd like to build a module that uses some externally-hosted javascript (Slickslider, for example).
It'd be neat if there were a way to do this without adding the Javascript to the page template - that way, the client could just drag-and-drop the module in, and it would automagically work. Is there a recommended method for doing this?
The file will then only be loaded when the module is actually used on the page. It will also only ever load once, regardless of how many module instances are on the page and how many other modules may call the library. Additionally if you only need it if say certain fields in your module are turned on, you can include that require statement in an if statement, and conditionally load the library.
The file will then only be loaded when the module is actually used on the page. It will also only ever load once, regardless of how many module instances are on the page and how many other modules may call the library. Additionally if you only need it if say certain fields in your module are turned on, you can include that require statement in an if statement, and conditionally load the library.
@amcintosh if this module is only ever going to use that one external script you could do it with JS like this
let executed = false;
function addScriptOnce() {
if(executed) {
return;
}
executed = true;
var s = document.createElement('script');
s.src='https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
addScriptOnce();
Or if you wanted the src to be a variable you could do it in the HubL like this
<script>
let executed = false;
function addScriptOnce() {
if(executed) {
return;
}
executed = true;
var s = document.createElement('script');
s.src=`{{module.external_script_url}}`;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
addScriptOnce();
</script>
I don't know of a way to get a count of how many times a module has been used inside a module sadly.
Thanks for the answer, but I was talking about external files served by a CDN (for example, https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.6/jquery.fancybox.min.js) - if you would rather use a file hosted by an outside source, it'd be nice to have a built-in way to include a link in a module, without having multiple instances of the module on a page include the link multiple times (as would happen if you just throw a <script> tag in there)