     for element in @getNewHeadProvisionalElements()
       document.head.appendChild(element)
 
-  importBodyPermanentElements: ->
-    for replaceableElement in @getNewBodyPermanentElements()
-      if permanentElement = @findCurrentBodyPermanentElement(replaceableElement)
-        importPermanentElement(permanentElement, replaceableElement)
+  extractCurrentBodyPermanentElements: ->
+    for permanentElement in @getCurrentBodyPermanentElements() when @findNewBodyPermanentElementById(permanentElement.id)
+      placeholder = createPlaceholderForPermanentElement(permanentElement)
+      replaceElementWithElement(permanentElement, placeholder)
+      permanentElement
 
-  activateBodyScriptElements: ->
-    for replaceableElement in @getNewBodyScriptElements()
-      element = @createScriptElement(replaceableElement)
-      replaceableElement.parentNode.replaceChild(element, replaceableElement)
+  replaceNewBodyPermanentElements: (permanentElements) ->
+    for permanentElement in permanentElements
+      if newElement = @findNewBodyPermanentElementById(permanentElement.id)
+        replaceElementWithElement(newElement, permanentElement)
+
+  replacePlaceholdersForPermanentElements: (permanentElements) ->
+    for permanentElement in permanentElements
+      if placeholder = @findPlaceholderById(permanentElement.id)
+        clonedElement = permanentElement.cloneNode(true)
+        replaceElementWithElement(placeholder, clonedElement)
+
+  activateNewBodyScriptElements: ->
+    for inertScriptElement in @getNewBodyScriptElements()
+      activatedScriptElement = @createScriptElement(inertScriptElement)
+      replaceElementWithElement(inertScriptElement, activatedScriptElement)
 
   assignNewBody: ->
     document.body = @newBody

  getNewHeadProvisionalElements: ->
    @newHeadDetails.getProvisionalElements()

  getNewBodyPermanentElements: ->
    @newBody.querySelectorAll("[id][data-turbolinks-permanent]")

  findCurrentBodyPermanentElement: (element) ->
    document.body.querySelector("##{element.id}[data-turbolinks-permanent]")

  getNewBodyScriptElements: ->
    @newBody.querySelectorAll("script")

  findFirstAutofocusableElement: ->
    document.body.querySelector("[autofocus]")

  importPermanentElement = (permanentElement, replaceableElement) ->
    permanentElement.parentNode.replaceChild(permanentElement.cloneNode(true), permanentElement)
    replaceableElement.parentNode.replaceChild(permanentElement, replaceableElement)
    permanentElement

    @copyNewHeadProvisionalElements()

  replaceBody: ->
    permanentElements = @extractCurrentBodyPermanentElements()
    @activateNewBodyScriptElements()
    @assignNewBody()
    @replaceNewBodyPermanentElements(permanentElements)
    @replacePlaceholdersForPermanentElements(permanentElements)

  shouldRender: ->
    @newSnapshot.isVisitable() and @trackedElementsAreIdentical()
