wp-search-with-algolia icon indicating copy to clipboard operation
wp-search-with-algolia copied to clipboard

Remove jQuery usage from shipped templates

Open tw2113 opened this issue 3 years ago • 6 comments

Let's remove jQuery from the autocomplete.php and instantsearch.php templates in favor of vanilla javascript.

tw2113 avatar Sep 15 '22 20:09 tw2113

Got this started in https://github.com/WebDevStudios/wp-search-with-algolia/tree/feature/231-remove-jquery-in-templates

Needs some review/confirmation on the changing of this:

jQuery( '#algolia-search-box input' ).attr( 'type', 'search' ).trigger( 'select' );

to something else.

As is, I have:

document.querySelector("#algolia-search-box input[type='search']").dispatchEvent(new Event('select'));

but I don't believe I'm matching things up properly yet.

tw2113 avatar Sep 24 '22 00:09 tw2113

@tw2113 It turns out we have select method for selecting text in vanilla JavaScript as well 😄

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

So your code will change to:

document.querySelector( "#algolia-search-box input[type='search']" ).select();

asharirfan avatar Sep 26 '22 16:09 asharirfan

I have almost all of autocomplete.php converted except for https://github.com/WebDevStudios/wp-search-with-algolia/blob/feature/231-remove-jquery-in-templates/templates/autocomplete.php#L192-L196

I tried addEventListener but it threw errors so I'm not doing some part correct.

I also interestingly needed to update the input_selector at https://github.com/WebDevStudios/wp-search-with-algolia/blob/feature/231-remove-jquery-in-templates/includes/class-algolia-template-loader.php#L84-L86 to make it find the inputs. Specifically the ' in the not was apparently not valid.

We're close!

tw2113 avatar Sep 26 '22 21:09 tw2113

I'm wondering if this lingering spot is maybe ok, based on https://github.com/WebDevStudios/wp-search-with-algolia/blob/main/js/autocomplete.js/dist/autocomplete.js#L1283-L1315

I don't believe the $ is a jQuery object in this case, and I think they rolled their own .on

tw2113 avatar Sep 26 '22 23:09 tw2113

@tw2113 Looks good to me. They have defined their own on function to detect events in the autocomplete UI.

asharirfan avatar Sep 27 '22 20:09 asharirfan

With that handled, I believe we have everything converted to working vanilla JS, but we should probably make sure to have it well tested, as well as where possible, notify existing users that we're making these changes.

We could add a new sticky thread at the top of https://wordpress.org/support/plugin/wp-search-with-algolia/ as needed.

Looking at our stats, 83% of our users are on version 2.1 or higher, 17%-ish on 1.8 or earlier. No version 1.9 released, and 2.0 may be in "other"

https://wordpress.org/plugins/wp-search-with-algolia/advanced/

tw2113 avatar Sep 27 '22 21:09 tw2113

Closing as done as this was merged in with #247

tw2113 avatar Oct 27 '22 21:10 tw2113