Skip to content

01. Getting Started

Michael Rhodes edited this page Apr 30, 2022 · 2 revisions

HelloWorld: A Simple Sargasso Custom Element

This simple example shows how to load the framework and define a simple Sargasso element controller that says "Hello World!". Sargasso custom element controllers are javascript Objects that are subclasses of the framework's Sargasso class. Custom behavior is defined by overriding various public methods of the base class.

Define a Simple Sargasso Custom Element

example/example1.html

<!-- sargasso custom element tag is the class name in KebabCase -->
<sargasso-hello-world></sargasso-hello-world>

<script type="module">
  import { Sargasso, utils } from "@pelagiccreatures/sargasso"

  // define HelloWorld as a subclass of Sargasso, classname in CamelCase
  class HelloWorld extends Sargasso {
    start() {
      // use an animation frame
      this.queueFrame(() => {
        this.element.innerHTML = 'Hello World!'
      })
      super.start()
    }
  }

  // Register HelloWorld class as a custom element
  utils.registerSargassoClass('HelloWorld', HelloWorld)

  // Start Sargasso
  utils.bootSargasso()
</script>

Try It

Using Custom Element Tags

All major current browsers support custom elements (current compatibility The tag name is the kebab-case of your subclass name so MyClass becomes sargasso-my-class:

<sargasso-my-class>This works in <em>all reasonably modern</em> browsers</sargasso-my-class>

Multiple sargasso classes can be supplied as unary attributes on the custom element tag.

<sargasso-my-class sargasso-my-other-class>This works in <em>all reasonably modern</em> browsers.</sargasso-my-class>

Using data-sargasso-class attribute to specify Sargasso classname

Sargasso watches the DOM for any elements tagged with the data-sargasso-class attribute which can contain one classname or a list of classnames. Use this method when attaching Sargasso controllers to standard html elements such as body, button, form etc.

<body data-sargasso-class="MyClass, MyOtherClass">This works in all browsers</body>

Lazy Loading

You can optionally defer the instantiation of Sargasso elements by using the lazy tagging method with data-lazy-sargasso-class instead of data-sargasso-class which will only start up the controller when the element becomes visible in the viewport.