4

How to check if jQuery library exist in head tags?

<head>
<script type="javascript/text" src="http://code.jquery.com/jquery-1.6.2.js"></script>
</head>

and if not exist how do I load in head tags the jquery library, I'm doing a plugins and I want to load my plugins script in jQuery and also do able to check if jQuery library exist so my jQuery script will run

4 Answers 4

7

scripts and styles should never be embedded directly in themes or templates because of potential conflicts between plugins and themes.

To use jQuery in a plugin or theme it should be enqueued with wp enqueue script. This will make sure it's added only once, and any scripts that define it as a dependency will load after.

2
  • so you mean wp ennqueue script does the checking and if its already exist it will not load the jQuery library in wp plugins? Commented Aug 8, 2011 at 4:56
  • yes, enqueue jQuery and enqueue whatever scripts your plugin uses with jQuery set as a dependency, and WP will handle it.
    – Milo
    Commented Aug 8, 2011 at 5:01
7

You can check whether the jQuery library already exist/loaded in the site and load it if not using the following code.

function load_jquery() {
    if ( ! wp_script_is( 'jquery', 'enqueued' )) {

        //Enqueue
        wp_enqueue_script( 'jquery' );

    }
}
add_action( 'wp_enqueue_scripts', 'load_jquery' );
0
3

Use this way to check jquery class loaded or not loaded.

if (jQuery) {  
    alert('Jquery Loaded');
} else {
    alert('Jquery Not Loaded');
}
2

@Milo already pointed this out, just enqueue your script with jQuery listed as a dependency. When WordPress loads your script, it will see the dependency and load jQuery for you automatically. For example:

function enqueue_my_scripts(){
    if( ! is_admin() )
        wp_enqueue_script( 'stacked-script', get_bloginfo('stylesheet_directory') . '/scripts/stacked.js', array('jquery'), '1.0.1' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );

Will put the following in the header of your site:

<script type='text/javascript' src='http://site-url.com/wp-includes/js/jquery/jquery.js?ver=1.6.1'></script> 
<script type='text/javascript' src='http://site-url.com/wp-content/themes/stacked-theme/scripts/stacked.js?ver=1.0.1'></script> 

jQuery will be loaded first, followed by your script.

1
  • This answer is very old. Now you can use admin_enqueue_scripts instead of wp_enqueue_scripts and remove the is_admin() check.
    – Gavin
    Commented Apr 16, 2020 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.