PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

[FIXED] what is the best way to include libraries?

 January 08, 2022     javascript, jquery, wordpress     No comments   

Issue

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!!!


Solution

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);


Answered By - Emiel Zuurbier
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing