WordPress: How to load all styles and scripts in footer
We want to load styles and scripts in footer in wordpress to load it faster. In fact the best practice is to load styles in head and the scripts in footer. We can use some minify plugins to minify all styles and/or scripts. But sometimes it creates issues, in most cases in SSL enabled pages minified styles do no work.
Also, we donâ€™t have control in third party plugins, some plugins pushes scripts in head and some pushes in footer. So, itâ€™s not possible to go through all plugins and make changes.
I have a little code snippet that will force to load all styles and scripts into the footer. Basically the logic is to remove action from head and adding it back to the footer.
Here you go:
remove_action(â€˜wp_headâ€™, â€˜wp_print_head_scriptsâ€™, 9);
remove_action(â€˜wp_headâ€™, â€˜wp_enqueue_scriptsâ€™, 1);
add_action(â€˜wp_footerâ€™, â€˜wp_print_scriptsâ€™, 5);
add_action(â€˜wp_footerâ€™, â€˜wp_enqueue_scriptsâ€™, 5);
add_action(â€˜wp_footerâ€™, â€˜wp_print_head_scriptsâ€™, 5);
You can add those codes in your functions.php in the theme, if you think your theme wonâ€™t be changed. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name â€˜mu-pluginsâ€™. If there is no folder in that name, then create a folder, name it â€˜mu-pluginsâ€™, create a file inside that, give any name you like and paste the code in there. You donâ€™t need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always. If you use mu-plugins then add a php start tag at the beginning of the code.
Please note that, this is still dangerous, it could break your site but in most cases it should work. You can give it a go and check