Add image lazy load for markdown
This commit is contained in:
parent
42eb5115d1
commit
b43772c3e5
5 changed files with 18 additions and 4 deletions
|
@ -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
|
||||
|
|
|
@ -41,4 +41,5 @@ pandas
|
|||
markdown
|
||||
bleach
|
||||
pymdown-extensions
|
||||
mdx-breakless-lists
|
||||
mdx-breakless-lists
|
||||
beautifulsoup4
|
|
@ -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) {
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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>
|
||||
|
|
Loading…
Reference in a new issue