Marketo Forms 2.0 datepicker/polyfill bug w/multiple forms

Just discovered another bug in Marketo forms when there's more than one form on the same page.

Symptoms: seemingly random behavior in loading the datepicker (or any other polyfill) in browsers that lack native support.

For example, Firefox does not support the native HTML <input type="date"> field, so the Forms 2.0 library loads a custom, JavaScript-based picker plugin (script-driven emulations of native features are called polyfills).

This works fine when there's only one form. When there's more than one form on the page, though, there's a race condition. If the first form to finish loading doesn't have a date field, the library doesn't load the polyfill. (The global library config is shared among all forms on the page, a wise choice in general but problematic in this case.)

So you'll see the datepicker either load or not depending on network, browser, and server conditions at a given moment:

ss
ss

This kind of seemingly random behavior almost always signals a network-level race. Blocks of asynchronous code do not run in predictable order. Even if network conditions usually favor one particular order (i.e. the order in which MktoForms2.loadForm calls appear in the code), that order can't be relied upon.

(This inescapable fact affects all kinds of code, from amateur copy-and-paste snippets to professional codebases.)

To circumvent the bug, this tiny bit of JavaScript causes the library to recheck the necessary polyfills for each form:

Object.defineProperty(MktoForms2,'_polyfillsLoaded',{
  value: false
});

Place after <SCRIPT src="//landingpages.example.com/path/to/forms2.min.js"> but before any calls to MktoForms2.loadForm.

And yes, there are other ways to work around the problem as well, like making sure a form with a date field loads first and loading the other forms in that form's ready listener. That's harder to maintain, though.