Add image lazy load for markdown

This commit is contained in:
cuom1999 2022-10-29 01:25:22 -05:00
parent 42eb5115d1
commit b43772c3e5
5 changed files with 18 additions and 4 deletions

View file

@ -2,6 +2,7 @@ from .. import registry
import markdown as _markdown
import bleach
from django.utils.html import escape
from bs4 import BeautifulSoup
EXTENSIONS = [
@ -57,10 +58,16 @@ ALLOWED_ATTRS = ["src", "width", "height", "href", "class", "open"]
@registry.filter
def markdown(value):
def markdown(value, lazy_load=False):
extensions = EXTENSIONS
html = _markdown.markdown(value, extensions=extensions)
html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS)
if not html:
html = escape(value)
if lazy_load:
soup = BeautifulSoup(html, features="lxml")
for img in soup.findAll("img"):
img["data-src"] = img["src"]
img["src"] = ""
html = str(soup)
return '<div class="md-typeset">%s</div>' % html

View file

@ -41,4 +41,5 @@ pandas
markdown
bleach
pymdown-extensions
mdx-breakless-lists
mdx-breakless-lists
beautifulsoup4

View file

@ -174,6 +174,12 @@ $(function () {
xhr.setRequestHeader('X-CSRFToken', $.cookie('csrftoken'));
}
});
setTimeout(() => {
$("[data-src]img").each(function() {
$(this).attr("src", $(this).attr("data-src"));
})
}, "500");
});
if (!Date.now) {

View file

@ -82,7 +82,7 @@
{% if user.about %}
<h4>{{ _('About') }}</h4>
{% cache 86400 'user_about' user.id MATH_ENGINE %}
{{ user.about|markdown|reference|str|safe }}
{{ user.about|markdown(lazy_load=True)|reference|str|safe }}
{% endcache %}
{% else %}
<i>

View file

@ -38,7 +38,7 @@
<div class="about-td">
{% if user.about %}
{% cache 86400 'user_about' user.id MATH_ENGINE %}
{{ user.about|markdown|reference|str|safe }}
{{ user.about|markdown(lazy_load=True)|reference|str|safe }}
{% endcache %}
{% endif %}
</div>