WordPress.org

Make WordPress Core

Opened 5 months ago

Last modified 2 months ago

#26113 new defect (bug)

Create a WordPress-specific, dependable reference to the WP-bundled jQuery object.

Reported by: markjaquith Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Script Loader Keywords:
Focuses: javascript Cc:

Description

When enqueueing jQuery for use on the front end of a site in a plugin or theme, a common concern is that the theme or another plugin has injected its own version of jQuery (probably an older version). This causes no end of support headaches for me as a plugin author.

I've recently taken drastic measures in one of my plugins:

I'm hooking in to wp_enqueue_scripts at -9999 and starting a buffer, then collecting it at wp_head 9999. I'm looking for the WP-included jQuery script tag, and then inserting this immediately after it:

<script>jQueryWP = jQuery;</script>

Then in my JS, I do:

;(function (w) {
    var jQ = w.jQueryWP || w.jQuery;
    // my jQuery code here, using jQ
})(window);

I think that having a dependable reference to WP's jQuery object would be quite useful. One way to solve it would be to just add the line to our copy of jQuery. But that will cause issues with people who use well-behaved CDN plugins to swap out WP's jQuery for a Google-hosted copy of jQuery (note: THE SAME VERSION). So maybe a better way to do it would be to create a way to append inline JS code immediately after the inclusion of a particular script handle. We could then do what I'm doing in my plugin, but without the nasty PHP output buffers.

Change History (3)

comment:1 wonderboymusic5 months ago

This might be a good stop gap, but our thinking about JS as a whole needs a reboot. There is a systemic problem of relying on global scope everywhere all over WordPress JS code.

We should really switch to using dependency injection via RequireJS or something similar. The NYTimes used a similar stopgap measure to prevent stomping - currently uses an NYTD.jQuery object equal to the first jQuery object on the page - great, right? Doesn't stop other code from loading jQuery 3-4 times elsewhere (+ 2 Prototypes + a Scriptaculous or 2). When using AMD + dependency injection, global scope never matters, so stomping is rarely possible.

comment:2 jdgrimes5 months ago

  • Cc jdg@… added

comment:3 nacin2 months ago

  • Component changed from Themes to Script Loader
  • Focuses javascript added

wp.jQuery would be nice to have. The need to append something after jQuery's inclusion is also useful for noConflict, which a CDN plugin also currently stomps.

FWIW, agreed on the need for an eventual reboot, but I think we're a few releases away from even seriously considering such a shift.

Note: See TracTickets for help on using tickets.