I have finally managed to combine all my WordPress Javascript from my theme and plugins into a single bundle using the function below:
function merge_all_scripts() {
global $wp_scripts;
$wp_scripts -> all_deps($wp_scripts -> queue);
$merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'merged-script.js';
$merged_script = '';
foreach( $wp_scripts->to_do as $handle) {
$src = strtok($wp_scripts->registered[$handle]->src, '?');
if (strpos($src, 'http') !== false) {
$site_url = site_url();
if (strpos($src, $site_url) !== false) $js_file_path = str_replace($site_url, '', $src);
else $js_file_path = $src;
$js_file_path = ltrim($js_file_path, '/');
} else {
$js_file_path = ltrim($src, '/');
}
if (file_exists($js_file_path)) {
$localize = '';
if (@key_exists('data', $wp_scripts->registered[$handle]->extra)) {
$localize = $obj->extra['data'] . ';';
}
$merged_script .= $localize . file_get_contents($js_file_path) . ';';
}
}
file_put_contents ( $merged_file_location , $merged_script);
wp_enqueue_script('merged-script', get_stylesheet_directory_uri() . '/merged-script.js', array(), '1.0', false );
foreach( $wp_scripts->to_do as $handle ) {
wp_deregister_script($handle);
}
}
add_action( 'wp_enqueue_scripts', 'merge_all_scripts', 99 );
Problem is it erases all inline woocommerce js defined in the "get_script_data" woocommerce function. I want it to include that aswell.
Otherwise content such as this will not get injected into the DOM, and therefore prevent the site from working properly:
var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","wc_ajax_url":"\/?wc-ajax=%%endpoint%%","i18n_view_cart":"Se kurv","cart_url":"https:\/\/lawrence.dk\/bag\/","is_cart":"","cart_redirect_after_add":"no"};