Cutting the Size of the Mautic JavaScript Tracking Script

Size of Mautic tracking script

Having used Mautic for a few clients, I decided to install it on my own site, partly for testing and partly to actually use it's functionality.

Unfortunately, having made an effort to keep my page sizes to a bare minimum, it was depressing to see that the tracking script increased the overall size of my pages by around 50%.

So I took a look at the script to see if it's size could be cut down.

Uncompressed, the default script weighs in at 130KB (64KB when gzipped). In comparison, this is double the size of Google analytics tracking and about 20KB under the size of the full jQuery library.

Opening up the file, you can see that the script contains all the code necessary for the full range of features that Mautic provides. A big chunk of that code is related to gated videos, which includes a shim for older browsers and a jQuery script for a media player.

As I don't use gated videos or jQuery, this is the first thing I want to look at removing.

The mtc.js file is built by mautic and then cached, so it doesn't just exist to be modified.

Searching through the files shows that the media player scripts are added in /app/bundles/PageBundle/EventListener/BuildJsSubscriber.php

The function getSubscribedEvents adds 2 chunks of js to the output, the actual page tracking, and the video code.

 /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            CoreEvents::BUILD_MAUTIC_JS => [
                ['onBuildJs', 255],
                ['onBuildJsForVideo', 256],
            ],
        ];
    }

Commenting out the line '['onBuildJsForVideo', 256],' will remove the video js from the tracking code and cut the compressed size of the file down to 45KB, 2/3 of the original file size.

NOTE: This is a hack and not a proper fix. It will stop the gated video functionality from working and the changes will be overwritten when Mautic is updated. There is probably a better way to do this with a plugin.