Streamline the Munchkin embed code, taking out outdated cruft
In my last post on the bfcache I mentioned the Munchkin library does some backward-compatible stuff that’s not necessary in modern browsers (it was only relevant for old versions of Internet Explorer).
In fact, the Munchkin embed code is also needlessly verbose. All you need to be compatible with the latest Chrome/Edge, Firefox, and Safari, on desktop and mobile, is this:
{
const munchkinBootstrap = document.createElement("script");
munchkinBootstrap.src = "//munchkin.marketo.net/munchkin-beta.js";
munchkinBootstrap.addEventListener("load", function(e) {
Munchkin.init("123-ABC-456"); // plus your custom Munchkin options, if any
},
{
once: true
});
document.head.append(munchkinBootstrap);
};(That could also have line breaks removed, but I wanted it to be readable.)
Contrast this with the default “async embed code” in the Marketo UI:
var didInit = false;
function initMunchkin() {
if(didInit === false) {
didInit = true;
Munchkin.init("123-ABC-456"); // plus your custom Munchkin options, if any
}
}
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//munchkin.marketo.net/munchkin-beta.js';
s.onreadystatechange = function() {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
initMunchkin();
}
};
s.onload = initMunchkin;
document.getElementsByTagName('head')[0].appendChild(s);My changes were:
- using block scope instead of a function
- switching
vartoconst - running the event handler
onceinstead of thedidInitflag (there are cases where you still need a separate flag, but not here) - removing explicit
typeandasync(those are the HTML5 defaults) - assuming there’s only one
<head>(let’s be serious, if you have duplicate<head>tags, things should break) - removing
onreadystatechange, which was only fired in IE
If you want your site to look new-ish to those peeking under the hood, use the newer snippet. Doesn’t change how Munchkin works, just how it’s loaded.