Elm Language Getting started with Elm Language Embedding into HTML


Example

There are three possibilities to insert Elm code into a existing HTML page.

Embed into the body tag

Supposing you have compiled the Hello World example into elm.js file, you can let Elm take over the <body> tag like so:

<!DOCTYPE html>
<html>
    <body>
        <script src="elm.js"></script>
        <script>
          Elm.Main.fullscreen()
        </script>
    </body>
</html>

WARNING: Sometimes some chrome extensions mess with <body> which can cause your app to break in production. It's recommended to always embed in a specific div. More info here.

Embed into a Div (or other DOM node)

Alternatively, by providing concrete HTML element, Elm code can be run in that specific page element:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <div id='app'></div>
        <script src="elm.js"></script>
        <script>
            Elm.Main.embed(document.getElementById('app'))
        </script>
    </body>
</html>

Embed as a Web worker (no UI)

Elm code can also be started as a worker and communicate thru ports:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello Worker</title>
    </head>
    <body>
        <script src="elm.js"></script>
        <script>
            var app = Elm.Main.worker();
            app.ports.fromElmToJS.subscribe(function(world) {
                console.log(world)
            });
            app.ports.fromJSToElm.send('hello');
        </script>
    </body>
</html>