simonw / simonwillisonblog

The source code behind my blog
https://simonwillison.net/
Apache License 2.0
203 stars 19 forks source link

Support lite-youtube-embed #500

Closed simonw closed 1 month ago

simonw commented 1 month ago

I want to drop a YouTube video into a blogmark, but I don't want to load the full YouTube iframe on every page that includes that item.

I used https://github.com/paulirish/lite-youtube-embed before for https://datasette.io/ and I like it.

simonw commented 1 month ago

I could load the CSS and JS on every page just in case, but I'd like to only load them if they are needed.

Got Claude to write me this: https://gist.github.com/simonw/dc20aa7c98d0edc15f68982362e334e9

<script type="module">
  const config = [
    {"tag": "lite-youtube", "js": "/static/lite-yt-embed.js", "css": "/static/lite-yt-embed.css"}
  ];
  for (const {tag, js, css} of config) {
    if (document.querySelector(tag)) {
      if (css) {
        document.head.appendChild(
          Object.assign(document.createElement('link'), {
            rel: 'stylesheet',
            href: css
          })
        );
      }
      if (js) {
        await import(js);
      }
    }
  }
</script>
simonw commented 1 month ago

I experimented with adding this to the Blogmark class:

    def body(self):
        if self.use_markdown:
            md = Markdown()
            md.block_level_elements.append("lite-youtube")
            return mark_safe(md.convert(self.commentary))
        return self.commentary

Without that change, <lite-youtube ...> in Markdown would render in a paragraph like this: Which meant that

<p>Here is a tag:</p>
<p><lite-youtube title="Introduction to Datasette and sqlite-utils" videoid="7kDFBnXaw-c" playlabel="Play: Introduction to Datasette and sqlite-utils"></lite-youtube></p>
<p>Done.</p>

With that change, the <lite-youtube> tag was not wrapped in a paragraph.

But... it turns out it looks better on the page in the paragraph, so I dropped that change.

simonw commented 1 month ago

OK, it works. https://simonwillison.net/2024/Oct/22/knowledge-navigator/