WordPress plugin to defer js, using array of script handles

Hi there,

So, I’m just starting off building a minor WP plugin that’ll search for enqueued scripts, add them to an array, then use the values in that array to defer each script.

This is just to start, once this part works, I want to also exclude some scripts and then create a settings page so that users can select scripts form a dropdown or type in the scripts that they want deferred.

Can anyone tell me any noticeable issues with what I have so far?

function get_scripts() {
    global $wp_scripts;
    foreach ($wp_scripts->queue as $script) {
        $script_list = array();
        array_push($script_list, $script);

function add_defer_attribute($tag, $handle) {
   // add script handles to the array below
   $scripts_to_defer = $script_list;
   foreach($scripts_to_defer as $defer_script) {
      if ($defer_script === $handle) {
         return str_replace(' src', ' defer="defer" src', $tag);
   return $tag;

add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);

why u dont use a plugins?

Hi gthemee,

This is an option, yes. However, beside the learning opportunity of building this myself. I’m looking for something lightweight that performs only this function, and no other functions. All it is going to be tasked with doing is find enqueued scripts, load to footer instead.

At another stage, I’m adding, exclude certain scripts using priority, and do not defer those, and a settings page where you can select scripts to defer or add your own, using their handles or script names.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.