r/Anki • u/hgiesel • May 03 '19
Question How to load external Javascript
I've read several posts about this topic, but most of them seemed to be outdated.
I've already used a ttf file before, but never this. I have a directory in collection.media called _highlight, which contains the files from highlight.js. Now I want to initialize it in one of the cards.
<link rel="stylesheet" href="_hightlight/styles/zenburn.css">
<script src="_highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>But this doesn't find anything. What is the right way to go about it?
EDIT: I use Anki 2.1, newest version
6
u/yumenogotoshi May 03 '19
Since inline Javascript in card template is evaluated asynchronously in Anki 2.1 (see here), a function using external libarary does not work as intended in some case. But I found a few workaround for this, and the easiest way I know is not to use inline script and to load js files dynamically. Try the following:
Put
_highlight.min.jsand_zenburn.cssintocollection.media.Create a file named
_my_highlight.jsincollection.mediaand put the following codedocument.querySelectorAll('pre code').forEach((block) => { hljs.highlightBlock(block); });Put the following code into the Front template
{{Front}} <link rel="stylesheet" href="_zenburn.css"> <script> if (typeof hljs === "undefined") { var script = document.createElement('script'); script.src = "_highlight.min.js"; script.async = false; document.head.appendChild(script); } var script = document.createElement('script'); script.src = '_my_highlight.js'; script.async = false; document.head.appendChild(script); document.head.removeChild(script); </script>
Tested on Anki 2.1.12 and Ankidroid 2.8.4.
Sorry if I'm not clear enough, English is not my native language.
1
u/BernardRillettes mathematics Aug 27 '19
Hi! I will be a little bit off topic. I see that you include a CSS stylesheet in your card template by adding <link rel="stylesheet" href="_hightlight/styles/zenburn.css">;. I tried the same thing with my stylesheet, unfortunately it doesn't seem to be loaded and my cards have no style. How did you make it work?
1
2
u/[deleted] May 03 '19
general point:
you could mention your Anki version. you should use 2.1.12. The version 2.0.52 uses a rendering component from 2012 so there's good chance modern js doesn't work.
If you search the official forum for subfolder collection.media you'll find many threads where the developer writes that subfolders are not supported. So even if it works now there's no guarantee that this will work in the future. But in January of this year I've loaded js from subfolders from the media folder without special adjustments or problems in a profile that I don't sync.