在加载所有异步功能之前先加载页面

时间:2019-09-06 14:14:39

标签: javascript jquery html

我有一个script ,其中包含两个异步函数,该页面会立即加载,但是我有一个值,这些值在其中一个异步函数中已更新 ,因此当我尝试向页面请求时,页面返回空白值,我的想法是保持页面加载,直到执行并完成所有异步功能为止。

脚本功能:

  <script>

    let thresh = 0.1

    async function updateResults() {
      if (!isFaceDetectionModelLoaded()) {
        return
      }

      const inputImgEl = $('#inputImg').get(0)
      const options = getFaceDetectorOptions()

      const results = await faceapi.detectAllFaces(inputImgEl, options)
        // compute face landmarks to align faces for better accuracy
        .withFaceLandmarks()
        .withFaceExpressions()


      const canvas = $('#overlay').get(0)
      faceapi.matchDimensions(canvas, inputImgEl)

      const resizedResults = faceapi.resizeResults(results, inputImgEl)
      const minConfidence = 0.05
      faceapi.draw.drawDetections(canvas, resizedResults)
      faceapi.draw.drawFaceExpressions(canvas, resizedResults, minConfidence)

      var Resultado = JSON.stringify(resizedResults);

      //Procuro as classes
      var stringify = JSON.parse(Resultado);
      var neutro = stringify[0]['expressions']['neutro']
      var feliz = stringify[0]['expressions']['feliz']
      var bravo = stringify[0]['expressions']['bravo']
      var com_medo = stringify[0]['expressions']['com medo']
      var nojo = stringify[0]['expressions']['nojo']
      var surpreso = stringify[0]['expressions']['surpreso']
      var triste = stringify[0]['expressions']['triste']

      var res = stringify[0]['expressions']

      if(feliz == '1') {

        res = "Feliz"

      }


      console.log(feliz)

      console.log(stringify[0]['expressions']);

      $("#Resultado").text(res);




    }

    async function run() {
      // load face detection and face expression recognition models
      // and load face landmark model for face alignment
      await changeFaceDetector(SSD_MOBILENETV1)
      await faceapi.loadFaceLandmarkModel('/')
      await faceapi.loadFaceExpressionModel('/')
      // start processing image


      updateResults()
    }

    $(document).ready(function() {

      initImageSelectionControls('webcam.jpg', true)
      initFaceDetectionControls()      
      run()

    })
    var startTime = (new Date()).getTime();
    $(window).load(function () {
       var endTime = (new Date()).getTime();

       var millisecondsLoading = endTime - startTime;

       console.log(millisecondsLoading);

   });
  </script>

注意:

访问的链接是API,因此用户无权访问它。

1 个答案:

答案 0 :(得分:0)

async函数和<script async属性的全部要点是允许页面加载完成而不会以任何方式阻止它。

您可以在初始化时存储全局承诺:

var globalInitializationPromise = run();

然后其他任何代码都可以等待:

await globalInitializationPromise;
// do stuff

请记住,您在run()实现中忘记了等待:

async function run() {
  // load face detection and face expression recognition models
  // and load face landmark model for face alignment
  await changeFaceDetector(SSD_MOBILENETV1)
  await faceapi.loadFaceLandmarkModel('/')
  await faceapi.loadFaceExpressionModel('/')
  // start processing image

  /**AWAIT WAS MISSING HERE! **/ await updateResults()
}

此外,如果您的函数是异步的,则无需从$(document).ready运行它们。而是在脚本加载时立即运行它们。如果某个功能需要访问DOM内容,则应await做出此承诺或类似的操作:

const documentReadyPromise = new Promise(function (resolve) {
    if (document.readyState === 'complete') {
        resolve();
    } else {
        function onReady() {
            resolve();
            document.removeEventListener('DOMContentLoaded', onReady, true);
            window.removeEventListener('load', onReady, true);
        }
        document.addEventListener('DOMContentLoaded', onReady, true);
        window.addEventListener('load', onReady, true);
    }
});

然后,在访问DOM的函数中,请先执行以下操作:

async function updateResults() {
  if (!isFaceDetectionModelLoaded()) {
    return
  }
  // uses DOM, must wait for HTML:
  await documentReadyPromise;
  // now you can access DOM
  const inputImgEl = $('#inputImg').get(0)

遵循这些规则应该会对应用程序的初始化速度产生积极的影响,因为在HTML加载时您可以突然做很多事情。