Skip to content

Instantly share code, notes, and snippets.

@stefanmm
Created December 10, 2023 00:05
Show Gist options
  • Save stefanmm/24a47d87e6ba6e7ced983a91b3861184 to your computer and use it in GitHub Desktop.
Save stefanmm/24a47d87e6ba6e7ced983a91b3861184 to your computer and use it in GitHub Desktop.
Fix "Does not use passive listeners to improve scrolling performance" for WP comment-reply.min.js
function sm_fix_comment_reply_passive_listeners(){
// deregister inside wp_footer (and not inside init) in case other plugins try to register comment-reply after init
wp_deregister_script( 'comment-reply' );
// Do not load JS if not needed
if ( is_single() && comments_open() ) {
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Function checks if a given script is already loaded
function isScriptLoaded(src) {
return document.querySelector('script[src="' + src + '"]') ? true : false;
}
// When a reply link is clicked, check if reply-script is loaded. If not, load it and emulate the click
document.querySelectorAll(".comment-reply-link").forEach(function(link) {
link.addEventListener("click", function() {
if (!isScriptLoaded("/wp-includes/js/comment-reply.min.js")) {
var script = document.createElement('script');
script.src = "/wp-includes/js/comment-reply.min.js";
script.onload = function() {
emRepClick(link.getAttribute('data-commentid'));
};
document.head.appendChild(script);
}
});
});
// Function waits 50 ms before it emulates a click on the relevant reply link now that the reply script is loaded
function emRepClick(comId) {
sleep(50).then(function() {
document.querySelectorAll('[data-commentid="' + comId + '"]')[0].dispatchEvent(new Event('click'));
});
}
// Function does nothing, for a given amount of time
function sleep(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
});
</script>
<?php
}
}
add_action('wp_footer','sm_fix_comment_reply_passive_listeners');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment