Run Javascript ONCE

The traditional way may be to put a code on every page that check if the javascript is loaded:

window.onload = function () {
    if (localStorage.getItem("hasCodeRunBefore") === null) {
        //load code...
        localStorage.setItem("hasCodeRunBefore", true);
    }
}

Is it possible to call a “hidden” page that only runs ONCE regardless of? Like pseudo code:

func init() {
	tpl = template.Must(template.ParseGlob("public/tmpl/*.html"))
    load code into site for every windows (store in localStorage)?
}

With the sync package you can run something only one time:

Example:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once
	onceBody := func() {
		fmt.Println("Only once")
	}
	done := make(chan bool)
	for i := 0; i < 10; i++ {
		go func() {
			once.Do(onceBody)
			done <- true
		}()
	}
	for i := 0; i < 10; i++ {
		<-done
	}
}

Thanks! But how do I run the Javascript and store in localStorage?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.