
You are worried about the speed of your website . JavaScript can cause low speed . You can try Defer Parsing of JavaScript in WordPress . It allows the browser to render JavaScript only after it finishes loading the main content of a site. We do it without a plugin , just some line code .
Why Need to Use Defer Parsing of JavaScript?
HTML document contains text, code that renders various DOM elements, and resources such as images, stylesheets, and scripts.
The browser reads this HTML markup line by line. Additionally, the resources present on the page need to be downloaded. By default, the browser sequentially downloads these resources as it finds them in the document. The rendering of the web page only resumes once a resource has been downloaded.
The main fact is SEO . Because a slow website doesn’t rank on SEO. Your website doesn’t load fully until it finishes downloading all the JavaScript . You can use so many plugins for this issue . Other hand , if a visitor sees that page load slowly , visitors can be upset .
To solve this issue , We can use defer attribute on script tag , To delay the execution of a JavaScript file .
HTML example :
<script defer src=”your-file-name.js”></script>
Defer Parsing of JavaScript in WordPress:
It’s so simple , We need to load the defer attribute on script tag with php in WordPress. So many ways to load defer attribute script tags but I love to use the “script_loader_tag” hook and modified script tag .
Use this code :
add_filter( 'script_loader_tag', 'wpk_add_id_to_script', 10, 3 );
function wpk_add_id_to_script( $tag, $handle, $source ) {
if ( 'bootstrap' === $handle ) {
$tag = '<script type="text/javascript" defer src="' . $source . '" id="'.$handle.'"></script>';
} return $tag;
}
Description :
wordpress default hook “script_loader_tag” , we load 3 parameter $tag $handle, $source .
Tag : That means full script tag html .
Handle: This is the name of the file . example :
wp_enqueue_script('bootstrap', get_stylesheet_directory_uri() .'/assets/js/bootstrap.min.js', array('jquery'),’5.0.0’, true);
In this case , “bootstrap” Handle .
Source: This is the path of the file .
Conclusion:
You want to increase your site speed . you need to use optimizer plugins . But you need to know plugin developers use defer attributes dynamically . I want to show you how to use it normally .
Note: I will be happy if you catch my mistakes.