Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to later reference compressed hashes #1069

Open
PetrDlouhy opened this issue Aug 12, 2021 · 0 comments
Open

Allow to later reference compressed hashes #1069

PetrDlouhy opened this issue Aug 12, 2021 · 0 comments

Comments

@PetrDlouhy
Copy link

PetrDlouhy commented Aug 12, 2021

Allow to reference compressed hashes by compress name for later use.
Apart from #1032, I have another use-case for this: I would like to construct servicesworker.js for Progressive web app (https://github.com/silviolleite/django-pwa) with compressed scripts.
Copying the exact content of the compress tag is very inconvenient and will lead to bugs in the future, when I will fail to change the content at all places.

Although this might not be possible to achieve for online compression at all (or would be very difficult), for offline compression it is quite easily - we just need to store the name references in offline compress manifest or some other file.

I was even able to get the info from the current manifest.json (although it is a bit hacky and might not work at all times, because I use regexps to find the appropriate <script> tags. Here is my code for the compress_reference templatetag:

import re

from compressor import cache
from compressor.conf import settings
from django import template


register = template.Library()


def render_string(string):
    return string.replace(
        settings.COMPRESS_URL_PLACEHOLDER,
        str(settings.COMPRESS_URL)
    )


@register.simple_tag
def compress_reference(file_type, compress_name):
    r = re.compile(f'.*\\/CACHE\\/{file_type}\\/{compress_name}.*')
    f = filter(r.match, list(cache.get_offline_manifest().values()))
    file_strings = ('\n'.join(f)).split('\n')
    file_paths = set(re.sub('.*src="(.*)".*', "\\1", render_string(s)) for s in file_strings)
    file_paths = set(re.sub('.*href="([^"]*)".*', "\\1", s) for s in file_paths)
    return file_paths

I use it in my service worker this way:

    {% compress_reference "js" "scripts" as file_paths %}
    {% for path in file_paths %}
    '{{ path }}',
    {% endfor %}

(edit: I added fix for CSS styles to the templatetag code)
(edit1: de-duplicate the lists)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant