doc: anywidget _esm gets cached by the browser
Describe the bug
In jupyter a new ESM bundle is injected on each widget instantiation. On anywidget, that _esm block only gets executed once. This difference was surprising and led to a hard to track bug because I had a module level cache that I used in my widget.
If this means that the pageweight isn't bloated by multiple _esm blobs in marimo, that's actually a huge win for me. But the behavior is different, and I want to flag it in case anyone else runs into the same problem
Environment
Marimo.app
Replace this line with the output of marimo env. Leave the backticks in place.
Code to reproduce
https://marimo.io/p/@paddy-mullen/notebook-nth4ir
Note that ESMCreateTime remains the same between different invocations of the widget. In Jupyter each invocation gets a new ESMCreateTime.
import marimo
__generated_with = "0.11.14-dev6"
app = marimo.App(width="medium")
@app.cell
def _():
import anywidget
import traitlets
class TimeWidget(anywidget.AnyWidget):
# Widget front-end JavaScript code
_css = """
button {
padding: 5px !important;
border-radius: 5px !important;
background-color: #f0f0f0 !important;
&:hover {
background-color: lightblue !important;
color: white !important;
}
}
label {display:block}
"""
_esm = """
const ESMCreateTime = new Date();
function makeEl(_type, _inner) {
const el = document.createElement(_type)
el.innerHTML = _inner
return el;
}
function render({ model, el }) {
const renderTime = new Date();
let getCount = () => model.get("count");
let button = makeEl("button", `count is ${getCount()}`)
button.addEventListener("click", () => {
model.set("count", getCount() + 1);
model.save_changes();
});
model.on("change:count", () => {
button.innerHTML = `count is ${getCount()}`;
});
el.appendChild(button);
el.appendChild(makeEl("label", `ESMCreateTime ${ESMCreateTime} renderTime ${renderTime}`))
}
export default { render };
"""
# Stateful property that can be accessed by JavaScript & Python
count = traitlets.Int(0).tag(sync=True)
return TimeWidget, anywidget, traitlets
@app.cell
def _(TimeWidget):
TimeWidget()
return
@app.cell
def _(TimeWidget):
TimeWidget()
return
if __name__ == "__main__":
app.run()
@paddymul can you try this locally? We actually changed this semantics but haven't deployed to the playground yet.
We did try to be smart for performance, but there were too many cases we can't cover so we did revert to running the script with a new js module each time.
I see the same behavior locally. Note that ESMCreateTime is the same
marimo env
{
"marimo": "0.11.22",
"OS": "Darwin",
"OS Version": "22.6.0",
"Processor": "arm",
"Python Version": "3.13.1",
"Binaries": {
"Browser": "134.0.6998.89",
"Node": "v18.20.4"
},
"Dependencies": {
"click": "8.1.8",
"docutils": "0.21.2",
"itsdangerous": "2.2.0",
"jedi": "0.19.2",
"markdown": "3.7",
"narwhals": "1.31.0",
"packaging": "24.2",
"psutil": "7.0.0",
"pygments": "2.19.1",
"pymdown-extensions": "10.14.3",
"pyyaml": "6.0.2",
"ruff": "0.11.0",
"starlette": "0.46.1",
"tomlkit": "0.13.2",
"typing-extensions": "4.12.2",
"uvicorn": "0.34.0",
"websockets": "15.0.1"
},
"Optional Dependencies": {
"anywidget": "0.9.15",
"pandas": "2.2.3",
"polars": "1.22.0",
"pyarrow": "17.0.0"
},
"Experimental Flags": {}
}
FWIW I greatly prefer your approach to what anywidget does in Jupyter. Buckaroo is 3.8Mb of JS, and it really bloats doms and notebooks. I have 85Mb ipynb files locally because of this behavior.
I dont think this will affect many anywidget based projects. From what I have seen they are mostly simple wrappers around more complex imported JS modules.
The buckaroo is more complex because I use anywidgets react wrapper. I was having a very hard time reliably controlling the creation of the callback functions that I needed so I moved getSingleSRC to a module level function wrapped in _.once. I will refactor this with a memoized function based on id(self) of the calling widget from python. Open to other suggestions.
const getSingleSRC = _.once((model: any, setRespError) => {
const reqFn: RequestFN = (pa: PayloadArgs) => {
model.send({ type: 'infinite_request', payload_args: pa })
}
const src = new KeyAwareSmartRowCache(reqFn)
model.on("msg:custom", (msg: any, buffers: any[]) => {
if (msg?.type !== "infinite_resp") {
console.log("bailing not infinite_resp")
return
...
The main point is, this was a rough edge that caught me. I'm not sure the best way to write documentation so that others can avoid it, but I'm happy to spitball different explanations.
It took a while to debug this problem. At first I thought that messages weren't being properly routed back to the correct calling widget. I wrote some nice example widgets of sending messages back and forth between the frontend and backend. When these worked as expected, I dug into other bits of my code to figure out the problem.
https://marimo.io/p/dev/notebook-to2ne2-aqu79xp5wmykgbmjqylrmo
Oh i see what you are referring to is getting cached. I was thinking if the anywidget itself was getting created, but in your case, you are creating 2 instances of the same anywidget.
We won't be changing the semantics to instead download the same file multiple times; as you said, it can create a lot of unnecessary bloat, and it is not how it is done on the web.
We can document this somewhere though.
Hi! I'd like to add the documentation mentioned above, if that's still useful.
My plan is a short note on the anywidget page, after the custom widget example. It would say that widget instances with the same _esm share one loaded module, so top-level code runs once and top-level variables are shared. It would also say to keep per-instance state in the model, or inside render or initialize.
It's a docs-only change to docs/api/inputs/anywidget.md. Does that placement work for you? If so, I'll open a PR.
@namupta-max you can open a PR