Google Pagespeed Insight - 未捕获的ReferenceError:未定义runPagespeedCallbacks

时间:2018-05-29 10:49:03

标签: javascript pagespeed

我在此处遵循“编写您的第一个客户端应用程序指南”:https://developers.google.com/speed/docs/insights/v4/first-app

我使用完全相同的代码,但使用的是我自己的API_KEYURL_TO_GET_RESULTS_FOR

但是,它会在浏览器控制台中不断抛出此错误:

  

未捕获的ReferenceError:未定义runPagespeedCallbacks

它被定义为代码中有一个名为runPagespeedCallbacks(result)的函数。

以下是以下代码,但它与指南中的完全相同:

<script>
var API_URL = 'https://www.googleapis.com/pagespeedonline/v4/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';

// Object that will hold the callbacks that process results from the
// PageSpeed Insights API.
var callbacks = {}

// Invokes the PageSpeed Insights API. The response will contain
// JavaScript that invokes our callback with the PageSpeed results.
function runPagespeed() {
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.async = true;
  var query = [
    'url=' + URL_TO_GET_RESULTS_FOR,
    'callback=runPagespeedCallbacks',
    'key=' + API_KEY,
  ].join('&');
  s.src = API_URL + query;
  document.head.insertBefore(s, null);
}

// Our JSONP callback. Checks for errors, then invokes our callback handlers.
function runPagespeedCallbacks(result) {
  if (result.error) {
    var errors = result.error.errors;
    for (var i = 0, len = errors.length; i < len; ++i) {
      if (errors[i].reason == 'badRequest' && API_KEY == 'yourAPIKey') {
        alert('Please specify your Google API key in the API_KEY variable.');
      } else {
        // NOTE: your real production app should use a better
        // mechanism than alert() to communicate the error to the user.
        alert(errors[i].message);
      }
    }
    return;
  }

  // Dispatch to each function on the callbacks object.
  for (var fn in callbacks) {
    var f = callbacks[fn];
    if (typeof f == 'function') {
      callbacks[fn](result);
    }
  }
}

// Invoke the callback that fetches results. Async here so we're sure
// to discover any callbacks registered below, but this can be
// synchronous in your code.
setTimeout(runPagespeed, 0);
</script>

任何人都可以向我提供有关问题是什么或我做错了什么的信息吗?

1 个答案:

答案 0 :(得分:0)

问题是我使用Webpack编译代码。如果我能找到一种方法来使用Webpack,我会编辑它。

相关问题