You're building a plugin that uses a popular jQuery plugin. What if, instead of loading the script right away you want to check if that script is already loaded by the theme or another plugin?
Fortunately for us, it's easy as a pie to detect if a jQuery plugin is loaded. Take a look at the code:
if (jQuery().magnificPopup) {
// magnificPopup is loaded
} else {
// magnificPopup is NOT loaded
}
Now that we're able to check if a specific jQuery script is loaded, let's create the fallback. To load the jQuery plugin when it's not already enqueued, we will use the jQuery.getScript() function. This laods a JavaScript file from the server using a GET HTTP request, then execute it.
By default, $.getScript()
sets the cache setting to false
. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. Let's make sure the jQuery plugin gets cached.
$.ajaxSetup({
cache: true
});
$.getScript('//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js', function () {
// magnificPopup is loaded
});
In the above example, I'm loading the script from a CDN. I wouldn't recommend this method if you're developing a plugin that will be hosted on WordPress.org. Scroll down to see how to load a local script using jQuery.getScript()
function.
If the jQuery script isn't loaded, its associated stylesheet is most likely not loaded either. Loading a stylesheet with jQuery is extremely simple. Take a look at the code:
$('<link/>', {
rel: 'stylesheet',
href: '//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css'
}).appendTo('head');
Back in 2010, Otto wrote a great guide on how to do this effectively. Therefore, I won't go into details.
<?php
function pluginLoaded_scripts() {
// Enqueue a script with jQuery as a dependency.
wp_enqueue_script( 'pluginLoaded', get_template_directory_uri() . '/js/pluginLoaded.js', array( 'jquery' ), '1.0.0', true );
// Define our parameters
$params = array(
'styleUrl' => get_template_directory_uri() . '/css/vendor/magnific-popup.css',
'scriptUrl' => get_template_directory_uri() . '/js/vendor/jquery.magnific-popup.min.js',
);
// Create the JavaScript object
wp_localize_script( 'pluginLoaded', 'pluginLoadedParams', $params );
}
add_action( 'wp_enqueue_scripts', 'pluginLoaded_scripts' );
Please leave some feedback in the comments.