Display wp plugins script and style handle

If you are serious about your site optimization, there will be a point where you want to control all these additional scripts and stylesheets your plugins are loading on your site.

To do so you will need to know the handle that is used to identified the said stylesheets and and scripts.

One easy way is to have it displayed front end in your test environment.

Add the following code to your theme function.php:

function get_enqueued_scripts () {

    $scripts = wp_scripts();

    echo 'Enqueued scripts:
';

    foreach( $scripts->queue as $handle ) :

        echo $handle.' | ';

    endforeach;

    echo '
';

}
 add_action( 'wp_head', 'get_enqueued_scripts', 9999 ); 

And to get the handles of the enqueued style sheets:

function get_enqueued_styles () {

    $styles = wp_styles();

    echo 'Enqueued styles:
';

    foreach( $styles->queue as $handle ) :

        echo $handle.' | ';

    endforeach;

}
 add_action( 'wp_head', 'get_enqueued_styles', 9999); 

In case you don’t have a test environment (really?) you can display this info in the console, don’t forget to disable that after you are done optimizing your site.

Defer the execution of javascript and load js files in the footer

In a previous article we have seen how to manually concatenate scripts in your main theme to avoid loading multiple files.

In case you can’t concatenate some scripts here are two options to defer the exectution of the script until after the page has fully loaded or simply load a php script in the footer rather than in the header of your page.

Defer the execution of a script:

For your inline scripts:

<script defer> your script</script>

And it is exactly the same when the scripts are in an external file:

<script src="/path/to/your/script" defer></script>

Execute a function in the footer instead of the header.

In one of my plugn I had the case where I needed to fetch all the categories and product variation in jquery plugin that allow live display and filtering for a given search string. As such, the jquery is prepared in a php file that I then included in my theme header with and include function. Until I realize I can as easily load the script in the footer and avoid to overload my header.

In the index.php file of the plugin:

add_action('wp_header', 'PluginName::functionName);

simply becomes:

add_action('wp_footer', 'PluginName::functionName);

functionName is your plugin function that contains the include statement that should be loaded in the footer.

Control what javascript and css files your wordpress plugins load.

Javascript and css can heavily impact your page load time and the ability of google bots to render your page. The consequence on your ranking might be heavy in case the page to be marked as not mobile friendly due to this rendering issue.

A solution is to reduce the number of css and js files your wordpress site loading.

As you have noticed, many plugins load their own css and js in order to perform their function and nicely display the output, which is perfectly legitimate, although it might not be desirable for a web designer concern with performance, as you ought to be ;)

I am pretty sure I don’t need to make the matter clear, as you are reading this article but just in case, let’s recall here that on top of impacting your SEO as stated above, there is a 5% drop in sales for each 0.1 sec of load time (I am not sure I state that correctly but you got the idea).

So, what the solution you may ask, rightfully, so let’s dig into that without any further delay.

The strategy we will explore here is to dequeue the plugin css and js and concatenate it to your theme js and cs

Dequeue a plugins javascript file or css stylesheet:

To dequeue the script you want to concatenate add the following code
in your theme functions.php :


add_action('wp_print_styles', 'deregister_styles', 100);

function deregister_styles() {
  wp_deregister_style('name-of-style');
}

Merge Javascript and styling with your existing files

Locate the style or js you have deregistered and copy and paste it’s content in your theme css or js.

Test your site thoroughly to make sure there is no conflict. Paste the code in your stylesheet in the order they are loaded on your page. Once you are sure everything is displaying properly, you might merge the style rules and remove the duplicated one in case there are.

There are more advance technique to load css such as css preprocessing. which we will cover in further articles.

More info on this excellent article:
https://davidwalsh.name/remove-stylesheets

Tips:

In order to make sure you are removing the right css files from the queue, use the developper tool of your browser and inspect the element related to your plugin, you will which css rules affect them and from what file they come from. Once you have noted the name of the css file you know which one you need to copy to your own css rules and remove from the queue.

Batch convert images in webp

In case your server doesn’t allow Webp Express to auto generate webp images, or for any other reason, you might want to bulk convert images in webp.

On windows the best solution I found was to use https://www.imagemagick.org/script/convert.php

I needed to add some batch scripting to allow for bulk conversion 

I tested this code with the inconvenience that the file name retains .jpg and get appended with the webp extension, which is not suitable for my case use. I corrected that with a python script that I had ready at hand for batch renaming files. Here is the batch script:

cd C:\Users\Admin\Documents\webptest\2018\09
dir /B /A-D > list.txt
FOR /F “tokens=* delims=” %%x in (list.txt) DO magick convert %%x %%x.webp

While looking for a solution to remove the file extension, I found this nice code from stackoverflow that I modified to suit my needs:

@echo off
for /R “C:\Users\Admin\Documents\webptest\2018\10” %%f in (*.jpg) do (
magick convert %%f %%~nf.webp
)
pause

Tested and working. The file are saved in the directory containing the batch script.

Next-gen image format browser support

Google page speed insights encourage you to use next-gen image formats.

One question that should arise immediately is the one of compatibility. Google has already tried to push its highly efficient image format webp since launch in 2010 the 30th of September,   but without compatibility by competiting browsers such as safari, firefox or internet explorer and edge,  webmaster did not adopt it as it required browser detection to serve the proper image format to the corresponding browser or load a javascript file to insure compatibility.

Nowadays it is not one but three so-called “next-gen” format that are available on the market, each compatible with a single major browser. Although things are about to change for webp.

JPEG 2000: Safari and Safari Mobile, Chrome Mobile, Facebook on IOS, Google search app. about 14% market share all device included.

JPEG XR: internet explorer and edge

WebP: Chrome, Edge and Firefox 65 in 2019.  with

61.51% and soon 66% with Firefox compatibility.

As we can see the compatibility range for webp has increased although Apple format JPEG 2000 is perfectly at ease in mobile environment but represent only 14% market share globally.

source:

https://www.scientiamobile.com/jpeg-2000-jpeg-xr-support-browser/

https://www.zdnet.com/article/firefox-and-edge-add-support-for-googles-webp-image-format/

http://gs.statcounter.com/

 

Now that we have some information on the different picture formats market share, we need a  way to share the right image to the correct browser. You can achieve this by using srcset

Use srcset to select each file type. Srcset is an image property that lets you toggle between images based on various criteria, such as high-resolution displays which are typically only seen on newer laptops and mobile phones.”

https://shubox.io/blog/2018/05/10/choosing-the-right-next-gen-format-for-your-images/

We could ponder on the inability of the industry to make changes and agree on the adoption of a new single format required by the exponential rise of data transiting in our network and the corresponding needs of space in servers for caching and indexing those data, but I’d like to reflect on the opportunity to adopt not one but two or three of those format.

The strategy would be to take the advantage of lazy load to take the time to get the device browser and fetch the proper image version only when required, those keeping the page load time low.

To get the screen resolution with javascript:

window.screen.width *window.devicePixelRatio  window.screen.height * window.devicePixelRatio

Source: https://stackoverflow.com/questions/2242086/how-to-detect-the-screen-resolution-with-javascript

Knowing the screen resolution, we can then serve the best suited pictures.

Actually a better way to serve different picture depending on screen resolution would be to use srcset introduce with hml5:

<img alt="my awesome image"
  src="banner.jpeg"
  srcset="banner-HD.jpeg 2x, banner-phone.jpeg 640w, banner-phone-HD.jpeg 640w 2x">

“The above would serve banner-phone.jpeg to devices with viewport width under 640px, banner-phone-HD.jpeg to small screen high DPI devices, banner-HD.jpeg to high DPI devices with screens greater than 640px, and banner.jpeg to everything else.”

srouce: https://www.html5rocks.com/en/mobile/high-dpi/

The syntax I currently used is the following:

<picture>
  <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
  <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

The advantage here is to be able to use the media attribute and instead of the width use the screen resolution in dpi:

resolution Specifies the pixel density (dpi or dpcm) of the target display/paper.
“min-” and “max-” prefixes can be used.
Example: media=”print and (resolution:300dpi)”

And the good news is that it works with amp-img elements too:

<amp-img alt="Hummingbird"
  src="images/hummingbird-wide.jpg"
  width="640"
  height="457"
  layout="responsive"
  srcset="images/hummingbird-wide.jpg 640w,
            images/hummingbird-narrow.jpg 320w">
</amp-img>

Source: https://www.ampproject.org/docs/design/responsive/art_direction

last but not least it seems to work out of the box for webp with src picture as fallback:

<picture> 
<source srcset="img/awesomeWebPImage.webp" type="image/webp"> 
<source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
<img src="img/creakyOldJPEG.jpg" alt="Alt Text!"> 
</picture>

according to: https://css-tricks.com/using-webp-images/

why it works : https://developers.google.com/speed/webp/faq

HTML5 <picture> element

HTML5 supports a <picture> element, which allows you to list multiple, alternative image targets in priority order, such that a client will request the first candidate image that it can display properly. See this discussion on HTML5 Rocks. The <picture> element is supported by more browsers all the time.

source:

For high dpi screens, you will get the best results by serving pictures that are twice their size on screen and heavily compressed with image quality down to 20. The picture will look crispier on high dpi display than the uncompressed picture served full-size. The loss of quality on standard display will be minimal so you can even go with generalizing the process for all platform. The advantage on top of the crispiness on high-dpi is that the picture is actually lighter than the original.

But even more important in our case, we want to know what image format the browser supports.

As I plan to use implement amp, I looked at info about device detection and amp, and this stackoverflow pop-up and was quite satisfying:

https://stackoverflow.com/questions/37103814/how-does-the-server-know-when-to-serve-an-amp-page

Here is an async example code for webp:

async function supportsWebp() {
  if (!self.createImageBitmap) return false;
  
  const webpData = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=';
  const blob = await fetch(webpData).then(r => r.blob());
  return createImageBitmap(blob).then(() => true, () => false);
}

(async () => {
  if(await supportsWebp()) {
    console.log('does support');
  }
  else {
    console.log('does not support');
  }
})();

source: https://davidwalsh.name/detect-webp

a similar example is given in the google webp source given above.

Last thing to see will be the use of CSS sprite and we will have a complete overview on the question.

Remove emojis script and style from wordpress

Dequeue emojis related script in your theme or child-theme function.php by adding this few lines of code:

remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); 
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); 
remove_action( 'wp_print_styles', 'print_emoji_styles' ); 
remove_action( 'admin_print_styles', 'print_emoji_styles' );