Search code examples
javascriptpythoninlineminify

How to minify inline javascript with Python


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.


Solution

  • 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>