Created
December 4, 2018 23:28
-
-
Save Danetag/5d0175f0ea1f9167d633b9b828fce86b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// // Load Manifest Asset | |
$manifest = WP_DEBUG ? array('main.css' => '', 'main.js' => '') : json_decode(file_get_contents(dirname(__FILE__)."/static/manifest.json"), true); | |
/** | |
* Register Scripts(). | |
*/ | |
function register_scripts($manifest) { | |
// include the base style in the header. | |
$base_js = WP_DEBUG ? 'http://localhost:8080/bundle.js' : get_stylesheet_directory_uri() . ( '/static/'.$manifest['main.js'] ); | |
wp_register_script( | |
'base-script', // handle name. | |
$base_js, | |
null, // an array of dependent styles. | |
'1.0', // version number. | |
false // CSS media type. | |
); | |
wp_enqueue_script( 'base-script' ); | |
// remove JS | |
wp_deregister_script('jquery'); | |
} | |
add_action( 'wp_enqueue_scripts', function() use ( $manifest ) { register_scripts( $manifest ); } ); | |
// Add Critical CSS | |
function css_critical( $manifest) { | |
$css_file = file_get_contents(get_template_directory_uri() . ( '/static/'.$manifest['main.css'] )); | |
echo "<style>".$css_file."</style>"; | |
} | |
if (!WP_DEBUG) add_action( 'wp_head', function() use ( $manifest ) { css_critical( $manifest ); } , 100); | |
// remove wp version param from any enqueued scripts | |
function vc_remove_wp_ver_css_js( $src ) { | |
if ( strpos( $src, 'ver=' ) ) | |
$src = remove_query_arg( 'ver', $src ); | |
return $src; | |
} | |
add_filter( 'style_loader_src', 'vc_remove_wp_ver_css_js', 9999 ); | |
add_filter( 'script_loader_src', 'vc_remove_wp_ver_css_js', 9999 ); | |
// Add defer attribute | |
function add_defer_attribute($tag, $handle, $manifest) { | |
// add script handles to the array below | |
$scripts_to_defer = array('http://localhost:8080/bundle.js', get_stylesheet_directory_uri() . ( '/static/'.$manifest['main.js'] )); | |
foreach($scripts_to_defer as $defer_script) { | |
$pos = strrpos($tag, "src='".$defer_script."'"); | |
if ($pos !== false) { | |
return str_replace(' src', ' defer src', $tag); | |
} | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', function($tag, $handle) use ( $manifest ) { return add_defer_attribute( $tag, $handle, $manifest ); }, 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment