我试图获得桌面和移动设备的页面速度分数,然后将它们传递给#pgscore&& #pgscorem输入。
问题是在脚本结束时我总是得到var device ==' mobile'。它看起来像跳过循环。知道我怎么能解决它?
for (var r = 0; r < 2; r++) {
var API_KEY = 'mykey';
var device = '';
switch (r) {
case 0: device='desktop'; break;
case 1: device='mobile'; break;
};
alert(device);
var URL_TO_GET_RESULTS_FOR = 'http://www.stackoverflow.com' + '&strategy=' + device;
var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';
var callbacks = {}
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);
}
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 {
alert(errors[i].message);
}
}
return;
}
for (var fn in callbacks) {
var f = callbacks[fn];
if (typeof f == 'function') {
callbacks[fn](result);
}
}
}
setTimeout(runPagespeed, 0);
callbacks.displayPageSpeedScore = function(result) {
var score = result.score;
功能计数在那里。问题在这里......为什么我无法获得可变设备==&#39;桌面&#39;首先,然后在第二个循环&#39;移动&#39;?我总是能够移动&#39;。
switch (device) {
case 'desktop': $('#pgscore').val(score); break;
case 'mobile': $('#pgscorem').val(score); break;
};
};
};
答案 0 :(得分:0)
由于我只需要得分,我使用的是php
$jsonurl="https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&locale=pl_pl&$key";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json, true);
/* print_r(array_values($json_output));*/
echo $json_output['score'];