Lazy load images
This commit is contained in:
parent
677d752873
commit
67105db5a9
2 changed files with 42 additions and 1 deletions
35
articles/markdown.py
Normal file
35
articles/markdown.py
Normal file
|
@ -0,0 +1,35 @@
|
|||
from markdown import Markdown
|
||||
from markdown.extensions import Extension
|
||||
from markdown.inlinepatterns import (
|
||||
IMAGE_LINK_RE,
|
||||
IMAGE_REFERENCE_RE,
|
||||
ImageInlineProcessor,
|
||||
ImageReferenceInlineProcessor,
|
||||
)
|
||||
|
||||
|
||||
class LazyImageInlineProcessor(ImageInlineProcessor):
|
||||
def handleMatch(self, m, data):
|
||||
el, match_start, index = super().handleMatch(m, data)
|
||||
el.set("loading", "lazy")
|
||||
return el, match_start, index
|
||||
|
||||
|
||||
class LazyImageReferenceInlineProcessor(ImageReferenceInlineProcessor):
|
||||
def makeTag(self, href, title, text):
|
||||
el = super().makeTag(href, title, text)
|
||||
el.set("loading", "lazy")
|
||||
return el
|
||||
|
||||
|
||||
class LazyLoadingImageExtension(Extension):
|
||||
def extendMarkdown(self, md: Markdown):
|
||||
md.inlinePatterns.register(
|
||||
LazyImageInlineProcessor(IMAGE_LINK_RE, md), "image_link", 150
|
||||
)
|
||||
md.inlinePatterns.register(
|
||||
LazyImageReferenceInlineProcessor(IMAGE_REFERENCE_RE, md),
|
||||
"image_reference",
|
||||
140,
|
||||
)
|
||||
md.registerExtension(self)
|
|
@ -11,6 +11,8 @@ from django.urls import reverse
|
|||
from django.utils import timezone
|
||||
from markdown.extensions.codehilite import CodeHiliteExtension
|
||||
|
||||
from articles.markdown import LazyLoadingImageExtension
|
||||
|
||||
|
||||
class User(AbstractUser):
|
||||
pass
|
||||
|
@ -79,7 +81,11 @@ class Article(AdminUrlMixin, models.Model):
|
|||
|
||||
def get_formatted_content(self):
|
||||
md = markdown.Markdown(
|
||||
extensions=["extra", CodeHiliteExtension(linenums=False)]
|
||||
extensions=[
|
||||
"extra",
|
||||
CodeHiliteExtension(linenums=False),
|
||||
LazyLoadingImageExtension(),
|
||||
]
|
||||
)
|
||||
content = self.content
|
||||
content = re.sub(r"(\s)#(\w+)", r"\1\#\2", content)
|
||||
|
|
Reference in a new issue