Sage 9 Code Splitting

I think you could create a new entry in resources/assets/config.json to build a page-specific bundle and set up a page-specific enqueue the normal WordPress way.

It’s not quite the same thing, but I wrote about how to do this with stylesheets here:

Essentially you’ll add the entry like this:

theme-name/resources/assets/config.json

{
  "entry": {
    "main": [
      "./scripts/main.js",
      "./styles/main.scss"
    ],
    "heavypage": [
      "./scripts/heavypage.js"
    ],
    "customizer": [
      "./scripts/customizer.js"
    ]
  },
  "publicPath": "/app/themes/theme-name",
  "devUrl": "http://mysite.dev",
  "proxyUrl": "http://localhost:3000",
  "cacheBusting": "[name]_[hash:8]",
  "watch": [
    "app/**/*.php",
    "config/**/*.php",
    "resources/controllers/**/*.php",
    "resources/views/**/*.php"
  ]
}

And then conditionally enqueue the bundle:
theme-name/app/setup.php

/**
 * Theme assets
 */
add_action('wp_enqueue_scripts', function () {
  if($condition) {
    wp_enqueue_script('sage/heavypage.js', asset_path('scripts/heavypage.js'), ['jquery'], null, true);
  }
}, 100);

This is all untested, written on an iPad but this is the gist of what will work at least.

Does that help?

8 Likes