Javascript

为解决用户端缓存问题给 html 中的 js, css 添加/替换版本号

本文主要是介绍为解决用户端缓存问题给 html 中的 js, css 添加/替换版本号,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

为解决用户端缓存问题给 html 中的 js, css 添加/替换版本号

python with_version.py input.html v=0.0.1 output.html

import bs4
import sys


def param_merge(vstr, pstr):
    vsplit = vstr.split('=')
    pdict = {}
    for pkey in pstr.split('&'):
        psplit = pkey.split('=')
        pdict[psplit[0]] = psplit[1]
    pdict[vsplit[0]] = vsplit[1]
    pstr2_list = [k + '=' + pdict[k] for k in pdict]
    return pstr2_list


def main():
    if len(sys.argv) == 1 or (len(sys.argv) > 1 and sys.argv[1] == '--help'):
        print("""usage: python with_version.py input.html v=0.0.1 output.html""")
        return
    elif len(sys.argv) != 4:
        return

    html = sys.argv[1]
    vstr = sys.argv[2]
    output_html = sys.argv[3]

    # load the file
    with open(html, 'r', encoding='utf-8') as inf:
        txt = inf.read()
        soup = bs4.BeautifulSoup(txt, 'html.parser')

    for script in soup.find_all("script", recursive=True):
        src = script['src']
        if -1 == src.find('?'):
            script['src'] = src + '?' + vstr
        else:
            [src, pstr] = src.split('?')
            merged = param_merge(vstr, pstr)
            script['src'] = src + '?' + '&'.join(merged)

    for link in soup.find_all("link", recursive=True):
        href = link['href']
        if -1 == href.find('?'):
            link['href'] = href + '?' + vstr
        else:
            [href, pstr] = href.split('?')
            merged = param_merge(vstr, pstr)
            link['href'] = href + '?' + '&'.join(merged)

    # save the file again
    with open(output_html, "w", encoding='utf-8') as fout:
        fout.write(soup.prettify())


if __name__ == '__main__':
    main()


这篇关于为解决用户端缓存问题给 html 中的 js, css 添加/替换版本号的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!