polar

Running in the Browser

Polar code runs in the browser like any other ES module. This guide builds a small page from scratch.

Set up the project

Make a project whose only host is Browser:

[project]
name = "web"
hosts = ["Browser"]

Then write src/main.px. Std.Dom provides the Browser host and the Dom effect:

module Main

uses
  Std.Dom

hosts
  Browser

functions
  start() -> {} / {Dom} {
    Dom.append_text("h1", "Hello from Polar")
    Dom.append_text("p", "This paragraph was added by Polar code.")
  }

exports
  start

By convention, the browser entry point is called start. main is for programs started by polar run.

Build it

$ polar build
built web (1 file) into dist in 7ms

dist/main.js is an ES module. Because start uses an effect, it compiles to an async function:

import * as $rt from "./_polar/runtime.js";
import * as $Dom from "./_polar/std/Dom.js";

export async function start() {
  await $Dom.$bind$Dom.append_text("h1", "Hello from Polar");
  return await $Dom.$bind$Dom.append_text("p", "This paragraph was added by Polar code.");
}

Load it from a page

Import it with a module script:

<!doctype html>
<html>
  <body>
    <script type="module">
      import { start } from "./dist/main.js";

      start();
    </script>
  </body>
</html>

Browsers only load modules over HTTP, not from file:// URLs, so serve the folder with any static server:

$ python3 -m http.server 8000

Open http://localhost:8000 and you'll see the heading and paragraph.

The Dom effect

Dom is deliberately small. It's enough to put content on a page from Polar:

Operation Does
Dom.append_text(tag, text) Adds a new element with that text to the end of the body
Dom.append_html(html) Adds an HTML string to the end of the body
Dom.has(id) Whether an element with that id exists
Dom.set_html(id, html) Replaces the contents of the element with that id

For anything else, declare an effect of your own and bind it to JavaScript. That's exactly how Dom itself is written.

Tip: Keep rendering logic pure: functions that turn data into strings or HTML don't need Dom. Only the function that puts the result on the page does. Then the same code can render on the server too.

To talk to a server from the browser, read Bridges next.