In certain situation, we need a check to ensure that the jQuery plugin is already loaded before calling it. The appropriate scenarios include - check before calling the plugin itself or to load a plugin which is dependent on another plugin.
Check jQuery
We can use the below-mentioned code to check whether jQuery itself is loaded.
if( jQuery ) {
alert( "jQuery loaded!" );
}
else {
alert( "jQuery not found!" );
}
Check jQuery Plugin
Basically, all the jQuery plugins are namespaces on the jQuery scope. We need a check to ensure that the namespace is available within the jQuery scope as shown below.
// Test namespace
if( jQuery().<plugin name> ) {
// Plugin dependent code
}
// Example - Check whether datetimepicker is loaded
if( jQuery().datetimepicker ) {
jQuery( '.datetimepicker' ).datetimepicker( { format: 'Y-m-d H:i:00', step: 5 } );
}
You can also use jQuery.fn.pluginName to check whether the plugin is available as shown below. It might not work in certain situations where the plugin does not use the fn namespace.
// Test namespace
if( jQuery().fn.<plugin name> ) {
// Plugin dependent code
}
// OR
if( jQuery().fn.<plugin name> !== undefined ) {
// Plugin dependent code
}
// Example - Check whether datetimepicker is loaded
if( jQuery().fn.datetimepicker ) {
jQuery( '.datetimepicker' ).datetimepicker( { format: 'Y-m-d H:i:00', step: 5 } );
}
This is how we can check whether jQuery or jQuery plugins are loaded to further execute the code dependent on the jQuery plugin.