jetpack icon indicating copy to clipboard operation
jetpack copied to clipboard

Subscriptions: check if jQuery is loaded before to use it for Subscriptions

Open jeherve opened this issue 11 years ago • 5 comments

We use jQuery in the subscription widget here: https://github.com/Automattic/jetpack/blob/3.5/modules/subscriptions.php#L701

However some themes or plugins change the way jQuery is enqueued, and enqueue it in the footer instead, after our function has been added, thus creating a Javascript error.

We should handle these cases a bit better.

Reported here: https://wordpress.org/support/topic/feature-request-subscription-module?replies=1&view=all

jeherve avatar Apr 27 '15 16:04 jeherve

I can rewrite the JS to remove the jQuery dependency. Alternatively, is that part even necessary? There should be server side checks already that does this. The entire script block should probably be attached using the proper enqueuing mechanism anyway, so that it doesn't block the page rendering and allows for other plugin/theme developers to dequeue them if necessary.

ZhangYiJiang avatar May 11 '15 10:05 ZhangYiJiang

The entire script block should probably be attached using the proper enqueuing mechanism anyway

Unfortunately that's not possible right now. If we were to use wp_enqueue_script, the script would be enqueued on each and every page of your site, which isn't very great for performance. We could wrap the enqueue in a is_active_widget() check to make sure the Javascript is only enqueued when the subscriptions widget is in use, but that wouldn't work when the subscription form is added to a page or a post thanks to the [jetpack_subscription_form] shortcode (#).

I'm afraid the only solution left is to add the Javascript inline, as we've done. We'll need to check if jQuery exists before to use it, though.

jeherve avatar May 11 '15 17:05 jeherve

I'm afraid the only solution left is to add the Javascript inline, as we've done. We'll need to check if jQuery exists before to use it, though.

Another solution is to register the script via wp_register_script (make it rendered in footer) and only enqueue the script when shortcode and/or widget is rendered.

gedex avatar May 22 '15 04:05 gedex

We could indeed check with both has_shortcode() and is_active_widget() before to enqueue, but I don't know if it's worth going throughthe performance hit of 2 checks for such a small piece of Javascript.

I'll defer to @zinigor for a second opinion about this, since he reviewed the related Pull Request (#2115).

jeherve avatar May 22 '15 10:05 jeherve

Judging by how #2115 is turning out, it's going to work fine without jQuery dependency. So after testing and merging we can do whatever we like with this script. Although for such a small script I'd say it's better to leave it inline to save one HTTP request.

zinigor avatar May 22 '15 13:05 zinigor