In order to cope with the improvement of page speed on the site managed by WordPress, there was a request to exclude resources that prevented rendering, so I decided to add the defer attribute to the script tag.
So I wrote the following code on functions.php, but other js are no longer working, so I would like to know why.Also, is there a good way?
if(!(is_admin())){
// JS asynchronous read → add defer attribute
function replace_scripttag($tag){
if(!preg_match('/\b(defer|async)\b/',$tag)){
return str_replace("type='text/javascript', 'defer', $tag);
}
return$tag;
}
add_filter('script_loader_tag', 'replace_scripttag');
}
Also, this method gives the defer attribute, but I did not give it when I used the code below, referring to the site below.I would appreciate it if you could tell me the cause and how to improve it.
https://kinsta.com/blog/defer-parsing-of-javascript/ #functions
function prefer_parsing_of_js($url){
if(is_user_logged_in()return$url;//don't break WP Admin
if(FALSE===strpos($url, '.js') return$url;
if(strpos($url, 'jquery.js')return$url;
return str_replace('src', 'defer src', $url);
}
add_filter('script_loader_tag', 'defer_parsing_of_js', 10);
"This time, I was thinking of giving the ""defer attribute"" to ""exclude resources that interfere with rendering"", but if you have any other opinions such as ""this is better!"", please let me know."
Thank you for your cooperation.
If the change in the loading timing was reflected and the problem occurred, perhaps the dependency between the loading JS files has gone wrong.
In other words, if files A and B were dependent A→B, the problem was not because A→B was originally read in synchronous order, but since A was set to defer
, B was executed first, and global variables that needed to be read in A were not initialized.
In such a case, it depends on the JS execution environment, but dynamic import would be an effective means in this case.
© 2024 OneMinuteCode. All rights reserved.