This tiny Magento 2 module will allow you to easily lazy load scripts and styles by url.
composer require blackbird/external-resources-loader
php bin/magento setup:upgrade
blackbird.loadExternalResource('https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/js/splide.min.js')
.then(() => /* code which is executed after the lib has loaded */)
blackbird.loadExternalResource('https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/css/splide.min.css')
.then(() => /* code which is executed after the style has loaded */)
Promise.all([
blackbird.loadExternalResource('https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/js/splide.min.js'),
blackbird.loadExternalResource('https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/dist/css/splide.min.css')
]).then(() => /* code which is executed after the style and the lib has loaded */)
The loadExternalResource
method will load a script or a style depending on the url extension.
If the url doesn't end by .js
or .css
, you could lazy load resource using one of these 2 methods :
loadExternalScript
: load resource from a url that provides javascript contentloadExternalStyle
: load resource from a url that provides css content
For instance :
blackbird.loadExternalScript("<?= $block->getViewFileUrl('js/my-script') ?>")