0

The answers that I get only cover .js files but I need to minify something like this:

<script>
    window.addEventListener('load', function (e)
    {
        ...
    });
</script>

To this:

<script>window.addEventListener('load',function(e){...});</script>

Actually I use "htmlmin" to minify the HTML code before I write the files with it but the inline javascripts remain with the original format.

Any help what to do here? Maybe a new package to replace "htmlmin". Thanks in advance.

6
  • Don't use inline scripts, problem solved. Commented Jul 31, 2018 at 19:21
  • You are right but the inline javascript call functions that run only in that file, not the whole website. ;-) Commented Jul 31, 2018 at 19:23
  • There are a million other ways to do that without using inline scripts. Some day you're going to have a bug, in production, and spend an embarrassing amount of time figuring out that the undescriptive stack trace is being generated from an inline script. Friends don't let friends use inline scripts. They don't generate good stack traces, they're opaque to your tools (as you've discovered), they pollute the global namespace unless your careful, depending on your editor they may not play nice with auto indent/syntax highlighting, they can run afoul of CSPs, just not worth it. Commented Jul 31, 2018 at 19:38
  • OK, this script activate some actions on my personal blog: window.addEventListener('load',function(e) { bloggen.hscrollTables(); bloggen.switchButtons(); }); Commented Jul 31, 2018 at 19:57
  • Besides that, it also the Disqus and Analytics for each page. Disqus need an specific config por each file. Tell me how to deal with it. :-) Commented Jul 31, 2018 at 20:03

1 Answer 1

1

Using REST API from the site https://www.minifier.org/.

Disclaimer: The site is made by user @matthiasmullie https://stackoverflow.com/users/802993/matthiasmullie

Example here:

from bs4 import BeautifulSoup
import requests
import json

url = 'https://minify.minifier.org/'

data = """<script>
    window.addEventListener('load', function (e)
    {
        i = 4;
    });
    </script>
"""

soup = BeautifulSoup(data, 'lxml')
script = soup.select_one('script')
r = requests.post(url, data={"source":script.text, "type" :"js"})
json_data = json.loads(r.text)
script.clear()
script.append(json_data['minified'])

print(script)

It prints:

<script>window.addEventListener('load',function(e)
{i=4})</script>
Sign up to request clarification or add additional context in comments.

1 Comment

That help me a lot. Pity it is a library in PHP to import locally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.