从远程url下载并压缩js,css


之前一直在使用bootcdn.cn提供的CDN服务,没出过什么大问题,即使国庆第一天凌晨挂过,对它依旧信任。

但事与愿违,无意中打开查看源码,才发现竟然有那么多的css,js文件

<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/fancybox/3.1.25/jquery.fancybox.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/lazysizes/4.0.1/lazysizes.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.bootcss.com/particles.js/2.0.0/particles.min.js"></script>
<script src="https://cdn.bootcss.com/fancybox/3.1.25/jquery.fancybox.min.js"></script>

作为强迫症有些受不了,想要把这些合并成一个css文件或js文件

首先找到熟悉的python的webassets,但发现只能使用本地文件,又不想一个文件一个文件的下载下来,所以写了一段简单的代码,把下载文件并压缩文件合到一起

  • 下载文件
    def write_to_file(name, url):
        resp = requests.get(url)
        path = os.path.join("/tmp", name)
        with open(path, "w") as f:
            f.write(resp.text)
        return name
    
  • 压缩css
    from webassets import Bundle
    from webassets import Environment
    
    def asset_css(files):
        env = Environment(directory='/tmp', url='/media')
        css = Bundle(*files, filters='cssmin', output='/tmp/mine.css')
        env.register('css_all', css)
        print(env['css_all'].urls())
    
  • 压缩js
    def asset_js(files):
        env = Environment(directory='/tmp', url='/media')
        css = Bundle(*files, filters='jsmin', output='/tmp/mine.js')
        env.register('js_all', css)
        print(env['js_all'].urls())
    
  • 调用
    css_files = {
        "bootstrap.min.css": "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css",
        "font-awesome.min.css": "https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css",
        "jquery.fancybox.min.css": "https://cdn.bootcss.com/fancybox/3.1.25/jquery.fancybox.min.css"
    }
    
    js_files = {
        "lazysizes.min.js": "https://cdn.bootcss.com/lazysizes/4.0.1/lazysizes.min.js",
        "jquery.min.js": "https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js",
        "bootstrap.min.js": "https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js",
        "particles.min.js": "https://cdn.bootcss.com/particles.js/2.0.0/particles.min.js",
        "jquery.fancybox.min.js": "https://cdn.bootcss.com/fancybox/3.1.25/jquery.fancybox.min.js"
    }
    
    def main():
        files = []
        for name, url in css_files.items():
            files.append(write_to_file(name, url))
        asset_css(files)
    
        files = []
        for name, url in js_files.items():
            files.append(write_to_file(name, url))
        asset_js(files)
    
    
    if __name__ == '__main__':
        main()
    

然后把压缩的mine.cssmine.js上传到云存储,测试后发现一切正常, 唯有font-awesome缺少字体, 下载字体后手动上传到css文件的相对目录../fonts即可

为避免忘记,特此记录