jeffreyguenther / vue-turbolinks

A Vue mixin to fix Turbolinks caching
MIT License
287 stars 20 forks source link

Verify parent exists before setting outerHTML #39

Closed eric-hemasystems closed 3 years ago

eric-hemasystems commented 3 years ago

Sometimes a Vue components $el is detached from the document without going through $vm.destroy. This would most often happen when some ancestor element is cleared out such as:

ancestor.innerHTML = ''

When this happens Vue/Turbolinks is still calling $vm.destroy once the page change happens. This now unattached element still restores the original HTML per this plugin without a problem.

There is a small corner case scenario where instead of some ancestor being cleared out the immediate parent of $el is being cleared out. In this case parentElement of $el is automatically set to null by the browser.

When this plugin executes the:

this.$el.outerHTML = this.$cachedHTML

on Chrome a JS error is generate as outerHTML cannot be set when the parentElement is null.

This somewhat related to #31 but is a slight different corner case. To resolve, I am verifying there is a parentElement before setting outerHTML. If there is not a parentElement then likely restoring the HTML isn't all that relevant anyway.

For a contrived but reduced example of this problem please see the following example:

https://codesandbox.io/s/null-parent-bvgrl

Open up the console below the browser on the right and make sure you are running in Chrome (Firefox doesn't care if you set the outerHTML and there is no parent). Press the "Clear and Fire" button and you should get the error.

With this patch the error no longer occurs.

excid3 commented 3 years ago

LGTM, great catch @eric-hemasystems 👍