Reputation: 220
I want to speed up the loading of my wordpress website. I write a simple plugin that will add the defer attribute to some scripts that are used by the custom theme I've installed. I'm facing the issue that the site is locked to the preloader screen and no error is present in the chrome dev console nor xdebug error are showed. Maybe I'm doing something wrong, I don't know, is possible that the main javascript file that is responsable to load the theme are not loaded also if isn't present in the array of the scripts that are processed to add the defer attribute? All the scripts are dependencies of the theme and are using jQuery that is not part of the list. Any help will be appreciated.
class WP_scriptDefer {
private $scripts = [
'bootstrap.min.js',
'lazyload.min.js',
'viewportchecker.min.js',
'universal-parallax.min.js',
];
public function __construct()
{
$this->init();
}
public function init()
{
add_filter( 'script_loader_tag', [$this, 'deferScripts'], 10 );
}
public function deferScripts()
{
foreach( $this->scripts as $script ){
if( true == strpos($tag, $script) ){
return str_replace('src', 'defer="defer" src', $tag);
}
}
}
}
new WP_scriptDefer;
Upvotes: 0
Views: 379
Reputation: 220
After a day and also thanks to the suggestion of Dmitry I've found the correct way to let the plugin work. The array scripts needs to contain the names assigned inside the wp_enqueue_script()
of each script and not the file name. This isn't very clear over the web because usually this filter is applied directly inside the function.php
of a theme.
Here is the full working code:
<?php
class WP_deferScripts {
private $defer_scripts = [
'bootstrap',
'lazyload',
'swiper',
];
public function __construct()
{
add_filter( 'script_loader_tag', [$this, 'deferScripts'], 10, 2);
}
public function deferScripts( string $tag, string $handle ) : string
{
#var_dump($handle, $tag);
foreach( $this->defet_scripts as $script ){
if( $script === $handle ){
return str_replace('src', 'defer="defer" src', $tag);
}
}
return $tag;
}
}
?>
Upvotes: 0
Reputation: 4412
I edit your class, check it please:
class WP_scriptDefer
{
private $scripts = [
'bootstrap.min.js',
'lazyload.min.js',
'viewportchecker.min.js',
'universal-parallax.min.js',
];
public function __construct()
{
$this->init();
}
public function init()
{
add_filter('script_loader_tag', [ $this, 'deferScripts'], 10, 3);
}
public function deferScripts( $tag, $handle, $src )
{
foreach( $this->scripts as $script ){
if( true === strpos($tag, $script) ){
return str_replace('src', 'defer="defer" src', $tag);
}
}
return $tag;
}
}
new WP_scriptDefer;
Upvotes: 0