Skip to content

Get selector optimisation #134

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/core/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const definitions = [
const constants = {
helpUrlBase: 'https://dequeuniversity.com/rules/',
gridSize: 200,
selectorSimilarFilterLimit: 700,
results: [],
resultGroups: [],
resultGroupMap: {},
Expand Down
18 changes: 15 additions & 3 deletions lib/core/utils/get-selector.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import getNodeAttributes from './get-node-attributes';
import matchesSelector from './element-matches';
import isXHTML from './is-xhtml';
import getShadowSelector from './get-shadow-selector';
import memoize from './memoize';
import constants from '../../core/constants';

const ignoredAttributes = [
'class',
Expand Down Expand Up @@ -376,8 +378,8 @@ function generateSelector(elm, options, doc) {
} else {
selector = features;
}
if (!similar) {
similar = Array.from(doc.querySelectorAll(selector));
if (!similar || similar.length > constants.selectorSimilarFilterLimit) {
similar = findSimilar(doc, selector);
} else {
similar = similar.filter(item => {
return matchesSelector(item, selector);
Expand All @@ -401,6 +403,16 @@ function generateSelector(elm, options, doc) {
* @param {Object} optional options
* @returns {String|Array<String>} Unique CSS selector for the node
*/
export default function getSelector(elm, options) {
function getSelector(elm, options) {
return getShadowSelector(generateSelector, elm, options);
}

// Axe can call getSelector more than once for the same element because
// the same element can end up on multiple DqElements.
export default memoize(getSelector);

// Similar elements create similar selectors. If there are lots of similar elements on the page,
// axe ends up needing to run that same selector many times. We can memoize for a huge perf boost.
const findSimilar = memoize((doc, selector) =>
Array.from(doc.querySelectorAll(selector))
);
Loading