DEV Community

Cover image for One simple trick to increase Stimulus.js legacy browser compatibility
fiiv
fiiv

Posted on

One simple trick to increase Stimulus.js legacy browser compatibility

Stimulus.js states in its installation documentation:

Stimulus supports all evergreen, self-updating desktop and mobile browsers out of the box. Stimulus 3+ does not support Internet Explorer 11.

In my latest project, I found that older iOS Safari browsers also had trouble with one particular part of the code. To understand it, here's the basic sample Stimulus hello_controller.js:

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}
Enter fullscreen mode Exit fullscreen mode

The problem is here:

static targets = [ "name", "output" ]
Enter fullscreen mode Exit fullscreen mode

It will lead to the following error message on older Safari browsers:

SyntaxError: Unexpected token '='
Enter fullscreen mode Exit fullscreen mode

The issue is the static keyword. However, there's a simple workaround for this:

import { Controller } from "stimulus"

export default class extends Controller {
  static get targets() {
    return [ "name", "output" ]
  }

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}
Enter fullscreen mode Exit fullscreen mode

So, what did we do?

static get targets() {
  return [ "name", "output" ]
}
Enter fullscreen mode Exit fullscreen mode

Well, the static keyword to create static fields is only available in Safari after 14.4 (2020).

Compatibility table for static fields

BUT - static has been around for much longer to define methods (including getter methods with the get keyword), in Safari 8.4+ (2014).

Compatibility table for static keyword

With this simple trick (and honestly, it's not that much of a pain to refactor), you can extend support of your applications for an admittedly small segment of legacy audiences.

Top comments (1)

Collapse
 
kostjapalovic profile image
Kostja Appliku.com

Great trick/tip! Thanks for sharing!