鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ vue如何“動(dòng)態(tài)導(dǎo)入(import)”多個(gè)文件(文件、圖片、js庫)?

vue如何“動(dòng)態(tài)導(dǎo)入(import)”多個(gè)文件(文件、圖片、js庫)?

項(xiàng)目中需要用到一個(gè)動(dòng)畫,這個(gè)動(dòng)畫需要引入THREE、TWEEN庫,需要導(dǎo)入圖片文件json文件,但是在移動(dòng)端,這個(gè)動(dòng)畫是不需要的,想要在移動(dòng)端達(dá)到最佳性能,這個(gè)動(dòng)畫相關(guān)的資源必須通過動(dòng)態(tài)導(dǎo)入的方式來做,查看了vue的官方文檔——動(dòng)態(tài)導(dǎo)入,發(fā)現(xiàn)這個(gè)例子非常簡單,導(dǎo)致我不知道如何修改這個(gè)代碼,特來請(qǐng)教:

需要改進(jìn)的代碼如下:

import * as THREE from "three";
import * as TWEEN from "tween";

import sphereData from "../../assets/animation/Sphere.json";
import orb from "../../assets/animation/orb.png";
//省略更多導(dǎo)入資源

官方實(shí)例代碼如下:

return import(/* webpackChunkName: "lodash" */ 'lodash').then(_ => {
  var element = document.createElement('div');

  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;

}).catch(error => 'An error occurred while loading the component');

官方實(shí)例代碼中,只導(dǎo)入了一個(gè)文件,并且沒有命令,直接import '資源路勁',
那么我如何改進(jìn)上面的代碼呢?

補(bǔ)充:
錯(cuò)誤提示如下:
圖片描述

回答
編輯回答
慢半拍
const dependencies = {
}

// page's mainFunction
function mainFunction() {
  // Do something with sphereData and orb, ...
  // Check if sphereData defined before use it
  if (dependencies.sphereData) {
    // show the animation
  }
}

// is it desktop?
if (isDesktop) {
  Promise.all([
    import('../../assets/animation/Sphere.json'),
    import('../../assets/animation/orb.png'),
    // other dependencies
  ]).then(([
    sphere,
    orb,
    // other dependencies
  ]) => {
    dependencies.sphere = sphere
    dependencies.orb = orb
    // ...
    
    mainFunction()
  })
} else {
  mainFunction()
}

Promise.all 的用法參見:https://developer.mozilla.org...

注意有些瀏覽器下 Promise 需要 polyfill
寫得我好累~~~

2018年3月6日 01:49
編輯回答
孤酒
Promise.all([import('xxxx'), import('xxx')]).then(() => {})
2017年6月5日 12:49