The compatibility between Polymer JS and Rails Turbolinks is problematic

Currently, I am facing a challenge in integrating PolymerJs with a Ruby on Rails project that has Turbolinks enabled. The issue arises when I click on a link - the new page loads correctly but my Polymer components do not reinitialize. They appear as if no JavaScript has been executed on them at all.

In my setup, I have loaded the Polymer components and platform in the header, so they do not reload with the 'page changes' (as is the nature of Turbolinks - it only refreshes the body).

To address this issue, I found a workaround which involves manually refreshing specific elements like 'my-custom-element' and 'core-ajax' using the following code snippet:

custom_elements = document.querySelectorAll("my-custom-element, core-ajax ") 
for element in custom_elements 
  element.parentNode.replaceChild(element.cloneNode(), element) 

However, I am looking for a more effective and idiomatic solution. I have also attempted to recall the Polymer() function inside the element with no success. It seems to trigger properly, but there is no indication of Polymer attempting to reattach my elements or activate any further activity within the shadowDOM. Additionally, I experimented with preventDispose, but it did not work due to the server loading an entirely new body.

Is there a way to instruct Polymer/Platform to reinitialize all elements on the page? Which events should be triggered for this purpose?

If a full reinitialization is not feasible, how can I specifically initialize a particular Polymer element?

Answer №1

This content is specifically written for Turbolinks 4 and has not been tested in Turbolinks 5

When using Turbolinks, it replaces the Document Body by fetching it via replaceChild method.

To view the code snippet for this process, visit: https://github.com/rails/turbolinks/blob/master/lib/assets/javascripts/turbolinks.js.coffee#L97

document.documentElement.replaceChild(body, document.body);

In some cases, this action does not trigger the 'upgrading of elements' as the Observers do not fire. Two alternative solutions have been proposed to address this issue:

1. Importing the entire body

$(document).on "page:change", ->
   document.documentElement.replaceChild(document.importNode(document.body, true), document.body);

2. Importing only the specific registered Polymer Elements

$(document).on "page:change", ->
  for polymerElement in Polymer.elements
    for domElement in document.body.querySelectorAll(polymerElement.name)
      domElement.parentNode.replaceChild(document.importNode(domElement, true), domElement);

Update:

It appears that these solutions align with the recommended way to handle such situations according to official sources.

For further understanding, refer to: https://groups.google.com/forum/#!msg/polymer-dev/WaWbepYW97Q/XE3SQTyvyCUJ

Additionally, a use case is provided to explain why this step is necessary:

To see why you might want to avoid changing type when adopting, consider an element born in an that gets moved into the main document. You probably wouldn't want to go back through the lifecycle just because it moved to a new document...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sometimes, a record goes missing from a PHP/JSON array

When calling a PHP script to retrieve results and converting the array into a JavaScript array for a multiple choice quiz, I encountered an issue where certain records were missing unexpectedly. It seems to occur randomly as there is no specific pattern to ...

Encountered an issue retrieving audio during recording with Recorder.js

I've come across a scenario where I'm utilizing the Recorder.js Demo for recording audio. Interestingly, it works perfectly on Linux but encounters an issue when used on Windows. A pop-up alert stating "Error getting audio" shows up. Here's ...

Leveraging deep linking to launch the email application in react native

I am currently exploring the deeplink URL for the mail app on iOS. A scenario I have set up involves displaying an alert that, when the user clicks 'ok', redirects them to the default mail app. const openEmailApp = () => { if (Platform.OS ...

Error encountered while trying to render a Threejs FBX Object - undefined 404 (Resource not found)

I am facing an issue while loading a set of .fbx objects using FBXLoader on a WebXR App. window.fbxLoader.load("/assets/modelate_FBX/Vaza%208067134/Vaza 8067134.fbx", function( object ) { const flower = this.scene.children.find(c => c.name ...

Utilizing Axios to filter response.data in an API request

Looking to retrieve the latest 8 products based on their date? Take a look at the code snippet below: const newestProducts= []; axios.get("http://localhost:3003/products").then(response => { let products = response.data.sort(fu ...

How can I efficiently display three items per click when tapping into jQuery data?

Here is the code that I have been working on: jQuery(document).ready(function( $ ) { var $container = $('#homegrid').masonry({ isAnimated: true, itemSelector: '.home-blocks', columnWidth: '.grid-sizer ...

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Importing WebAssembly dynamically can sometimes lead to complications with the order of execution

I am attempting to load a WASM library from another node js application, both utilizing webpack. Within the WASM library, I have the following code snippet exporting the functionality. export default import("./pkg") .then(s => { le ...

What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3: Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage wit ...

bulk purchase discount with HTML/JavaScript/PHP

I am looking to add a slider feature to my "Prices" page in order to provide customers with an instant quote based on the quantity they select. The slider should range from 1 to 500 or even up to 1000, but having an input box for customers to enter the qu ...

How to insert a span element within a link tag in Next.js/React.js

Looking to create a breadcrumb using microdata in a Next.js and React.js project. Initially, I tried the following: <li itemProp="itemListElement" itemScope itemType="https://schema.org/ListItem"> <Link href={'/index&a ...

ValueError: Unable to perform slicing operation on this data

When attempting a query in nodejs, I encounter this error: [2017-08-19 19:06:55.946] [ERROR] error - TypeError: val.slice is not a function at escapeString (/var/www/Bot/node_modules/sqlstring/lib/SqlString.js:183:23) at Object.escape (/var/www/Bo ...

Issue with Route Transition in React Router version 4 when using Styled Components

I am currently in the process of constructing a React Application utilizing React-Router@4, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5e7d0d4d6c198fddac198f9dad4d1d0c7f5869bd7d0c1d49b83">[email protected]</a> ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

Update content without reloading the page

I've implemented a function to delete an image in my action.js file: export const removeImage = (id, image_id) => async () => { try { const response = await axios.delete( `localhost:3000//api/v1/posts/${id}/delete/${image_id}`, ...

Unable to get the onchange event to trigger for a span element

Is there a way to trigger the onchange event on a span element that doesn't seem to be working? Here is the code I am using: Attempt 1 document.getElementById(seconds).addEventListener('change', (event: MutationEvent & { path: any }) =& ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

Using addClass and removeClass functions in JQuery when selecting a radio button

I am facing an issue with my radio buttons being displayed as images. When a picture (radio button) is selected, I want the other pictures to become hidden. To achieve this, I plan to add a class to the checked picture and then add another class to the unc ...

Loading data with limit offset in AngularJS can lead to controller functions crashing and causing data to become jammed

I have developed a video gallery application similar to Youtube using AngularJS. The application includes a REST API which is accessed through Angular services. There are two controller files in the application with similar functionalities but calling diff ...