jejacks0n/mercury — pull request #328 by mikepack (2013-01-28 20:12:09+00:00)
Title: Fix double script execution

If I have a snippet which contains some JavaScript, the JavaScript will be executed twice upon page load. In my situation, this causes bugs because code is being executed against the same DOM multiple times.

The JavaScript must be in the snippet markup so that when the snippet is injected/reinjected, the JavaScript is executed. I'm not aware of any Mercury hooks for when a snippet is reinjected.

Eg:

**Snippet HTML**

```html

```

Upon page load, the result of the snippet's UL will be:

```html

test

test

```

The results should be:

```html

test

```

This change uses raw JS to capture the adjusted HTML and create a jQuery element for it. jQuery's `$('

').html('')` will execute the script immediately, even if it's not injected into the DOM, so this technique is avoided.

I thought through some alternative solutions that didn't require modifying Mercury but came up short. Unique IDs, data-loaded attributes, singleton objects, or moving JS outside the snippet were amongst them.