Use jQuery to check if an element exists and then load the jQuery plugin on demand.
In the process of front-end development, we will use a lot of jQuery plug-ins, jQuery plug-ins used more, it will lead to slower web page opening speed. The jQuery plugins that are introduced are not needed on every page. This time using on-demand loading method to load jQuery plugin will have a lot of front-end performance improvement help.
There are many ways to load on demand, today we'll talk about jQuery's method.
Methods for determining whether an element exists in a web page
var $selector = $('.my-element');
if ( $selector.length > 0 ) {
// If present, introduce the jQuery library or do something else
}Example of loading a jQuery plugin on demand
Here, we first determine if the page has a `.slideshow`, if it does, it means that the page has a slideshow, and we load `jquery.cycle.min.js`, the jQuery slideshow plugin.
var $slideshow = $('.slideshow');
if ( $slideshow.length > 0 ) {
$.getScript("js/jquery.cycle.min.js").done(function() {
$slideshow.cycle();
});
}If we need to use it often, we can also write a function function
jQuery.fn.exists = function(){ return this.length > 0; }
if ( $(selector).exists() ) {
// If it exists, introduce the jQuery library, or do something else
}In some cases where more page effects are required, the above method can reduce the loading speed of a certain page to a certain extent, thus improving the user experience.