-
Notifications
You must be signed in to change notification settings - Fork 1
/
onload.go
60 lines (54 loc) · 1.7 KB
/
onload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// +build js
// Package onload provides a minimal, cross-browser document onload trigger
// for GopherJS. It is adapted from http://stackoverflow.com/a/9899701/13860
package onload
import "github.com/gopherjs/gopherjs/js"
var readyList []func() = make([]func(), 0, 1)
var readyFired bool = false
var readyEventHandlersInstalled bool = false
// Ready registers a function to fire when the page is loaded. This is effectively
// the same as jQuery's $.ready(), but written in Go, and without the bloat of jQuery.
// Ready() may be called multiple times, and once the document is ready, registered
// functions will be called in registration order.
func Ready(fn func()) {
if readyFired {
go fn()
return
}
readyList = append(readyList, fn)
doc := js.Global.Get("document")
if doc.Get("readyState").String() == "complete" {
go ready()
return
}
if !readyEventHandlersInstalled {
if doc.Get("addEventListener") != js.Undefined {
// first choice is DOMContentLoaded event
doc.Call("addEventListener", "DOMContentLoaded", ready, false)
// backup is window load event
js.Global.Call("addEventListener", "load", ready, false)
} else {
// Must be IE
doc.Call("attachEvent", "onreadystatechange", readyStatechange)
js.Global.Call("attachEvent", "onload", ready)
}
readyEventHandlersInstalled = true
}
}
// ready does the actual work of running the registered functions when the
// document is finally ready
func ready() {
if !readyFired {
readyFired = true
for _, readyFunc := range readyList {
readyFunc()
}
readyList = nil
}
}
// readyStateChange is a ready() wrapper for IE
func readyStatechange() {
if js.Global.Get("document").Get("readyState").String() == "complete" {
ready()
}
}