vue递归动态加载静态文件

2020-12-26  本文已影响0人  张晓畅

上来就干货!

需求

index.html文件引入第三方资源(js/css),每次打包前需要将引入的文件路径修改为部署的环境路径,比较麻烦,需要将部署环境的服务改为可配置

方法

封装一个加载静态资源的js插件,提供一个回调函数,避免因文件异步加载而导致的变量依赖关系报错。

/**main.js*/
import Vue from 'vue'
import App from './App.vue'
import OnloadFile from './plugins/onloadFile'
// 调用示例 先加载静态资源再创建vue
const onloadFile = new OnloadFile(
  window.h5_config.STATIC_URL,
  window.h5_config.STATIC_FILES,
  () => {
  new Vue({
    render: h => h(App)
  }).$mount('#app')
});
onloadFile.reOption();
/**config.js*/ 
window.h5_config = {
    STATIC_URL: 'https://www.baidu.com',
    STATIC_FILES: [
        '/layout.js',
        '/layout.css'
    ]
}

config.js引入方式参照vue配置服务地址

/**
 * @param { String } baseurl 文件服务地址
 * @param { Array } paths 文件相对路径
 * @param { Function } callback 回调函数
 * 递归加载文件
 * 2、获取第i个路径后缀名
 * 3、创建并添加document节点
 * 4、判断文件是否加载完成
 * 5、递归上面的步骤
 * 6、结束递归动作
 * @example
 * const onloadFile = new OnloadFile(
 * 'https://baidu.com'
 * ['/layout.css', '/layout.js'],
 * () => { console.info('静态文件加载完'); }
 * )
 * onloadFile.reOption();
*/
const OnloadFile = function (baseurl, paths, callback) {
    this.index = 0;
    this.fullPath = ''; // 要加载的完整路径
    this.ext = ''; // 扩展名
    this.ele = null; // 创建的element
    // 获取后缀名
    this.getExt = function () {
        this.fullPath = baseurl + paths[this.index];
        var stare = this.fullPath.lastIndexOf('.') + 1,
            end = this.fullPath.length;
        this.ext = this.fullPath.substring(stare, end).toLowerCase();
    }
    // 引入js
    this.addjsFile = function () {
        this.ele = document.createElement('script');
        this.ele.src = this.fullPath;
        document.getElementsByTagName('head')[0].appendChild(this.ele);
    }
    // 引入css
    this.addcssFile = function () {
        this.ele = document.createElement('link');
        this.ele.rel = 'stylesheet'
        this.ele.href = this.fullPath;
        document.getElementsByTagName('head')[0].appendChild(this.ele);
    }
    // 文件是否加载完
    this.onloaded = function () {
        var _this = this;
        this.ele.onload = function () {
            _this.onloadCall();
        };
    }
    // 文件加载回调
    this.onloadCall = function () {
        console.info(this.fullPath)
        this.index++;
        if (this.index < paths.length) {
            this.reOption();
        } else {
            console.info('静态资源加载完')
            callback();
        }
    }
    // 递归动作
    this.reOption = function () {
        this.getExt();
        // this[`add${this.ext}File`]()  es6
        if (this.ext === 'js') {
            this.addjsFile();
        }
        if (this.ext == 'css') {
            this.addcssFile()
        }
        this.onloaded();
    }
}

export default OnloadFile
上一篇 下一篇

猜你喜欢

热点阅读