Flickering issue caused by JS

I’ve noticed that if I reference a JS file in my card template, the cards start to flash/flicker when they load. The template looks like this:

{{Front}}
<script src="_file.js"></script>

The screen becomes blank for a moment and then the card loads. This issue does not occur when I insert the JS code directly in the template, e.g. like this:

{{Front}}
<script>
// some code
</script>

Is this some kind of a bug in the Anki webview? I like the first method of importing JS code because it avoids code duplication — multiple note types can reference the same JS file, so I’d like to find a way to fix it.

4 Likes

Could the issue be caused by this? don't cache js files · ankitects/anki@972c9da · GitHub

2 Likes

Is the flickering fixed, if you import the js file like this:

<script>
var exportedFunction;
if (!exportedFunction) {
  import("/_file.js").then(moduleObj => {
    globalThis.exportedFunction = moduleObj.exportedFunction;
  });
</script>

This is basically implementing a kind of caching by taking advantage of the way global variables are kept between card renders on desktop.

Edit: Fixed import path missing /

1 Like

import("_file.js") doesn’t load anything, but import("/_file.js") does work.

I can’t notice the flickering when doing it this way, but it’s essentially the same thing as writing the code inside <script></script>, except it will probably work better if the script is large thanks to the caching. I wanted to use <script src="..."> because then I won’t have to repeat myself that much.

I have also tried changing max_age = 0 in qt/aqt/mediasrv.py to a larger number, but it didn’t fix it for some reason.

If you believe there’s been a regression, please bisect it. If the issue has always been there, maybe using the async or defer on the script tags will help.

I have tried both async and defer, but there was no difference. I think this is not a recent regression but rather something that has been present for a long time. I only recently tried adding a script file to collection.media and importing it in my card template, so I didn’t notice the issue before.

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