Async loading script

This might be more a general webpack question, but I’m trying to implement some font tracking code that requires the async loading of a tracking script. The supplied code is:

        var mtiTracking = document.createElement('script');
        mtiTracking.type='text/javascript';
        mtiTracking.async='true';
         mtiTracking.src='mtiFontTrackingCode.js';
        (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild( mtiTracking );
   })();

so I can put that in routes/Common.js - but how do I handle the src in this case ‘mtiFontTrackingCode.js’?

I added the file to config.json:

{
  "entry": {
    "main": [
      "./scripts/util/public-path.js",
      "./scripts/main.js",
      "./styles/main.scss"
    ],
    "customizer": [
      "./scripts/customizer.js"
    ],
    "mtiFontTrackingCode": [
      "./scripts/mtiFontTrackingCode.js"
    ]
  },
  "publicPath": "/app/themes/sage9",
  "devUrl": "http://redacted.dev"
}

which compiles the file to ‘dist’ on npm run build but what’s the propper way to use async loaded files in the dev environment?

As far as I know, you should remove it from your config.json and simply require it asynchronously from another script (like your Common.js), such as:

require.ensure([], () => {
    require('./mtiFontTrackingCode.js');
})

Hope it helps :slight_smile:

1 Like

Thanks - works perfectly :slight_smile: