How to control the order of the combination of enqueued styles and scripts – site speed issue

We know, using wp_head() and wp_footer() all the scripts and styles are enqueued using wp_enqueue_styles and wp_enqueue_scripts hook. What we do is to enqueue our stylesheets and scripts using functions.php. And similarly WordPress plugins also enqueue their stylesheets and scripts using the same method.

So, in the end there are many enqueued styles and scripts in header or footer. What Google PageSpeed recommends is:

Optimize the order of styles and scripts – Google PageSpeed

We know, wp_enqueue_script() and wp_enqueue_style() offer a $deps parameter, where we can define the depth or priority of the script or stylesheet. But that affects only within scripts and styles, not in both. So, with a combined load of scripts and stylesheets from the theme, and/or child theme, and/or plugins, and/or third party API etc. how can we let the WordPress to enqueue them all in a way so that site speed improves with a sound website’s quality?
Or, are they bulletproof to echo styles first, than scripts?

Solutions Collecting From Web of "How to control the order of the combination of enqueued styles and scripts – site speed issue"

I will try to answer this as best as possible given that there is no bulletproof method.

It’s up to the developer to really plan out how the DOM is painted, WordPress cannot guess as to what a theme/plugin/user is going to be doing, it can simply provide some guidance and basic tools. The problem of course is when many plugins are added to a site, you can have a mess on your hands. This is what separates a well crafted site structure from one hastily clicked into place.

The $deps does not really define priority, it only provides dependency context. You can actually define priority in the action hook using the $priority parameter. There is nothing wrong with using multiple wp_enqueue_scripts with different $priority settings.

Some pointers.

  • Come up with a load structure for your css/js, write it
    down, analyze it using Developer Tools, Firebug, etc, to inspect how the page
    is painted.
  • Use the wp_enqueue_scripts action for wp_enqueue_style
  • Use $priority and $in_footer for your actions
  • Load javascript asynchronously if possible, and load as little javascript as needed.
  • Cache everything

Example of inspecting frame loading in developer tools, mousing over these details provides more call stack info.
enter image description here