My first experiment with Web Assembly

27/08/2018 22:48 BST

Lately I decided to experiment with Web Assembly just to get the feel of the concept, on my first impression it’s was very nice. What I did is written a wasm app to interface with jQuery and use go html/template system, it worked, it fetches data from html using jQuery, fed it to the template than return rendered html back to jQuery and place in the #box.

package main

import (
	"bytes"
	"html/template"
	"io/ioutil"
	"net/http"
	"strings"
	"syscall/js"
)

func JQuery(args ...interface{}) js.Value {
	return js.Global().Call("jQuery", args...)
}

const htmlTemplate = `
<h2>{{ .Forename }} {{ .Surname }}</h2>
`

func checkAndUpdate(event js.Value, tpl *template.Template) {
	type context struct {
		Forename string
		Surname  string
	}
	buf := &bytes.Buffer{}
	tpl.Execute(buf, context{
		Forename: JQuery("#forename").Call("val").String(),
		Surname:  JQuery("#surname").Call("val").String(),
	})

	JQuery("#box").Call("html", buf.String())
}

func ipAddress() {
	res, _ := http.Get("https://icanhazip.com/")
	b, _ := ioutil.ReadAll(res.Body)

	JQuery("#ipAddress").Call("text", strings.TrimSpace(string(b)))
}

func main() {
	tpl := template.Must(template.New("template").Parse(htmlTemplate))

	JQuery("#forename, #surname").
		Call("on", "keyup", js.NewEventCallback(js.PreventDefault, func(event js.Value) {
			checkAndUpdate(event, tpl)
		}))

	ipAddress()

	select {}
}

As awesome, as it is, I wouldn’t get too excited yet, the only issue I have at the moment is the file size, it’s 9 megabyte or 1.5 megabyte compressed, but I’m confident that the gophers will get this issue fixed in future release of go.

Web Assembly IMHO, has got serious potentials for the future.

Source Code Web Assembly

It’s was fun experimenting with WASM. The idea of using binary inside a web browser is great.

| |