Optimy is a js-plugin for lazy loading of scripts, styles and other resources, which speeds up page loading on the client side. It works on the basis of the IntersectionObserver class.
For browsers that do not support the observer class, you must use the polyfill intersection-observer.js. There are two main ways to do this:
-
Connect in the HTML code using the script tag
<script src="/js/intersection-observer.js"></script> <script src="/js/optimy.js"></script>
-
Change the property
polyfillin your js file after connecting the pluginOptimy.polyfill = '/js/intersection-observer.js';
The methods loadStyle and loadScript load script and style accordingly and have arguments:
urlis a url (src/href) of resourceonloadis a function that will run after the resource is loadedisAsync(forloadScriptonly) is an argument that allows the script to load asynchronously (by default true)
loadResource is a common method for loading different resources and have three arguments:
tagis a html tag of resource (script,link)attrsis an object of tag attributesrunOnloadis an argument that runsonloadevent or don't if the resource has already been loaded (by default true).
That three methods will be loaded resource only once.
The methods lazyLoad (for lazy loading of img and backgrounds images) and obsLoad (for lazy loading of resouces) use IntersectionObserver class and have one argument:
settingsis an object in which you may to specify:targetsis may be a collection (NodeList) or an element (HTMLElement)callbackis a callback function. By default, thelazyLoadmethod uses a methodimagesCallbackthat runs the callback for every visible element in the viewport individually. For theobsLoadmethod you should to use the methodresourcesCallbackthat runs the callback once if some element becomes visible in the viewport.optionsis an object of IntersectionObserver options. You can read more about the options on the official website MDN.attribute(forlazyLoadonly) is an attribute name for lazy loading (by default data-src)loadingLazy(forlazyLoadonly) is a value for attributeloading="lazy"for a browser that supports this feature (by default true)
Example:
const targets = document.querySelectorAll('.swiper');
const observerObject = new Optimy.obsLoad({
targets: targets,
options: {
rootMargin: '30%',
threshold: 0.0
},
callback: Optimy.resourcesCallback(function() {
Optimy.loadStyle('/css/swiper.min.css', function() {
console.log('swiper.min.css has been loaded!');
Optimy.loadScript('/js/swiper-bundle.min.js', function() {
console.log('swiper-bundle.min.js has been loaded!');
});
});
})
});