0

I've got a problem with the jQuery supplied with WordPress. The following HTML exhibits this problem:

<!DOCTYPE html>
<html>
    <head>
        <script src='http://wordpress.myownserver/wp-includes/js/jquery/jquery.js?ver=1.8.3'></script>
    </head>
<body>
    <div id="something"></div>
    <script>if(window.jQuery) console.log("window.jQuery");</script>
    <script>window.jQuery || document.write('<script src="/res/jquery-1.8.3.min.js"><\/script>')</script>
    <script>
        $(document).ready(function () {
            $('#something').html('something');
        });
    </script>
</body>

This is a typical situation in my WordPress site, where WordPress's jQuery is included (for the admin bar) at <head>, and my own CDN / fallback jQuery is included before the end of </body>.

The console output of this page is:

window.jQuery
Uncaught TypeError: Property '$' of object [object Object] is not a function 

I can solve this problem in several ways, for instance, I could replace the jQuery <script> part in <body> to:

<script src="/res/jquery-1.8.3.min.js"></script>

Without the window.jQuery check. But this is not optimal considering I've included jQuery twice. I then tried replacing the <script> in <head> to:

<script src="/res/jquery-1.8.3.min.js"></script>

Surprisingly, this also solved the problem. I knew about wp_deregister_script, but for admin, this also disables jQuery in the dashboard.

I'd like to retain admin bar for admin. So currently the site only breaks (see console output above) when admin is logged in. I'm wondering if the jQuery supplied with WordPress is anything special. I'm using version 3.5.1, and I'm planning on using jQuery in my own theme. Should I just include it twice to address this issue?

1 Answer 1

2

There is a difference with the version of jQuery supplied with WordPress as outline on the Codex page for wp_enqueue_script:

Note: The jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load.

Change your script to reference the jQuery object with jQuery rather than $, passing the jQuery object as $ so you can use it as you normally would within:

jQuery(document).ready(function($) {
    $('#something').html('something');
});
0

Your Answer

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

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