Skip to content
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

Add a front end JQuery enqueue check #423

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
55 changes: 55 additions & 0 deletions checks/class-jquery-check.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php
/**
* Check if JQuery is enqueued on the front end.
*
* @package Theme Check
*/

/**
* Check if JQuery is enqueued on the front end.
*/
class JQuery_Check implements themecheck {
/**
* Error messages, warnings and info notices.
*
* @var array $error
*/
protected $error = array();

/**
* Check that return true for good/okay/acceptable, false for bad/not-okay/unacceptable.
*
* @param array $php_files File paths and content for PHP files.
* @param array $css_files File paths and content for CSS files.
* @param array $other_files Folder names, file paths and content for other files.
*/
public function check( $php_files, $css_files, $other_files ) {

$php = implode( ' ', $php_files );

checkcount();

if ( ! preg_match( '/wp_enqueue_script\(\s?("|\')jquery("|\')/i', $php ) ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will catch enqueueing jQuery successfully. However, it will not catch cases where jQuery is a dependency of another script - in which case it also gets loaded.
Most themes don't enqueue jQuery directly, it is simply used as a dependency for their own scripts, so we should check for that scenario as well.

$this->error[] = sprintf(
'<span class="tc-lead tc-warning">%s</span>: %s',
__( 'RECOMMENDED', 'theme-check' ),
sprintf(
'JQuery is enqueued on the front end, however you may not need it, see <a href="%s">this article</a> for tips on switching to vanilla JavaScript.',
'https://make.wordpress.org/themes/2021/10/04/the-performance-impact-of-using-jquery-in-wordpress-themes/'
)
);
}
return true;
}

/**
* Get error messages from the checks.
*
* @return array Error message.
*/
public function getError() {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

copied this bit from other classes, so i'm assuming it is required?

return $this->error;
}
}

$themechecks[] = new JQuery_Check();