I am trying to create a mobile carousel and the best thing I find is with the jquery mobile library, the problem is that when including it directly in the template it blocks the rendering.
By the way, I am using wordpress.
That is why my query is based on whether there is any good practice to include libraries (in my case jQuery Mobile) without damaging the load / or the pagespeed score for example.
From already thank you very much!!!
CodePudding user response:
You can always modify the output of the <script>
tag by adding a defer
attribute. This will make your (JS) script non-blocking.
Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating. MDN
Firstly wrap your wp_enqueue_script
and wp_enqueue_style
inside of a wp_enqueue_scripts
action handler. This is the proper way to register and enqueue scripts and styles WP Docs.
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('jqm_js', 'https://code.jquery.com/mobile/1.2./jquery.mobile-1.2.0.min.js', ['jquery'], '1.2.0');
wp_register_style('jqm_css', 'https://code.jquery.com/mobile/1.2./jquery.mobile-1.2.0.min.css', [], '1.2.0');
wp_enqueue_style('jqm_css',);
}, 10);
With the script_loader_tag
filter, you can modify how the <script>
tag is being generated. The following snippet will check for each script that is registered and enqueued if the handle is in the $handles
array. If it is, then it will add a defer
attribute to the script.
Modify the values in the $handles
array to add or remove any scripts that you want to defer.
add_filter('script_loader_tag', function ($tag, $handle, $src) {
$handles = ['jqm_js'];
if (in_array($handle, $handles)) {
$tag = str_replace(' src', ' defer="defer" src', $tag);
}
return $tag;
}, 10, 3);