Skip to Content

defer_async_scripts()

Add defer/async to script URLs as they are called by WordPress.

PHP April 26, 2017

Usage

This function runs automatically, so it is not called manually. Is this incorrect?

Additional Notes

This is not an ideal solution, but fills a gap until this is a feature of WordPress core.

Source File

Located in /libs/Optimization.php on line 181.

No Hooks

This function does not have any filters or actions available. Request one?
PHP
        public function defer_async_scripts($tag, $handle){
            if ( !$this->is_admin_page(true) ){
                $crossorigin_exececution = wp_scripts()->get_data($handle, 'crossorigin');
                $defer_exececution = wp_scripts()->get_data($handle, 'defer');
                $async_exececution = wp_scripts()->get_data($handle, 'async');
                $module_execution = wp_scripts()->get_data($handle, 'module');

                //Add module type attribute if it is requested
                if ( !empty($module_execution) && strpos($tag, "type='module'") === false ){
                    $tag = str_replace("type='text/javascript'", "type='module'", $tag); //Change the type='text/javascript' attribute to type='module'
                }

                //Add crossorigin attribute if it is requested and does not already exist
                if ( !empty($crossorigin_exececution) && strpos($tag, 'crossorigin=') === false ){
                    $tag = str_replace(' src', ' crossorigin="anonymous" src', $tag); //Add the crossorigin attribute
                }

                //Ignore if neither defer nor async attribute is found
                if ( empty($defer_exececution) && empty($async_exececution) ){
                    return $tag;
                }

                //Abort adding async/defer for scripts that have this script as a dependency...? Maybe not?
                /*
                    foreach ( wp_scripts()->registered as $script ){
                        if ( in_array($handle, $script->deps, true) ){
                            return $tag;
                        }
                    }
                */

                //Add defer attribute if it is requested and does not already exist
                if ( !empty($defer_exececution) && strpos($tag, 'defer=') === false ){
                    $tag = str_replace(' src', ' defer="defer" src', $tag); //Add the defer attribute
                }

                //Add async attribute if it is requested and does not already exist
                if ( !empty($async_exececution) && strpos($tag, 'async=') === false ){
                    $tag = str_replace(' src', ' async="async" src', $tag); //Add the async attribute
                }
            }

            return $tag;
        }

Override

This function can not be short-circuited with an override filter. Request one?