Javascript Facebook API中断页面的其余部分,直到加载数据
我使用FacebookJavaScriptSDK来提供一些功能,但它会使页面的其余部分的功能滞后/在加载完成之前无法工作。要体验这一点,请继续并单击(位置不好的)Facebook登录按钮,然后尝试单击答案框内的。或者,您也可以从下面的代码中找到一些内容:Javascript Facebook API中断页面的其余部分,直到加载数据,javascript,jquery,facebook,facebook-graph-api,facebook-javascript-sdk,Javascript,Jquery,Facebook,Facebook Graph Api,Facebook Javascript Sdk,我使用FacebookJavaScriptSDK来提供一些功能,但它会使页面的其余部分的功能滞后/在加载完成之前无法工作。要体验这一点,请继续并单击(位置不好的)Facebook登录按钮,然后尝试单击答案框内的。或者,您也可以从下面的代码中找到一些内容: <!DOCTYPE HTML> <html> <head> <title>Speedsums - do maths fast</title> <script> (
<!DOCTYPE HTML>
<html>
<head>
<title>Speedsums - do maths fast</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46469577-1', 'speedsums.com');
ga('send', 'pageview');
</script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
<style type="text/css">
css stuff
</style>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="jquery.runner-min.js" type="text/javascript"></script>
<script src="chart.js" type="text/javascript"></script>
<script src="jquery.animate-colors-min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var data2;
var jsonn;
var myLine;
</script>
<script type="text/javascript">
var fbid;var fbid = 0;
var operators = ['+','-','x','\xF7'];
var properties = {
borderColor: 'green',
borderWidth: '3px',
height: '37px'
};
var user = {};
var friends = [];
var friendscores = [];
var friendpics = [];
var fbconnect;
var operand1;
var operand2;
var operator;
var answers;
var time;
var name;
var one;
var two;
var iteration = 0;
var unique;
var times = [];
var start;
var finish;
function drawuserchart(id){
console.log('drawuserchart() initialised');
$.ajax({
url: 'userchart.php',
data: {id: id},
type: 'post',
dataType:"json",
success: function(data22){
console.log(data22);
var labelarray = new Array();
for (var i=0;i<data22.length;i++) {
labelarray.push("");
}
data2 = {
labels : labelarray,
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(131,167,185,1)",
data : data22
}
]
}
var options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
}
myLine2 = new Chart(document.getElementById("userchart").getContext("2d")).Line(data2,options);
}, error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
function generateproblems(number){
operand1 = []; operand2 = []; operator = []; answers = [];
for (var i=0; i < number; i++){
//generating questions
operator.push(operators[Math.floor(Math.random() * 4)]);
if (operator[i] == '\xF7'){
denominator = Math.floor((Math.random()*12)+1);
numerator = denominator * Math.floor((Math.random()*12)+1);
operand1.push(numerator);
operand2.push(denominator);
} else if (operator[i] == '-'){
one = Math.floor((Math.random()*12)+1);
two = Math.floor((Math.random()*12)+1);
operand1.push(Math.max(one,two));
operand2.push(Math.min(one,two));
} else {
operand1.push(Math.floor((Math.random()*12)+1));
operand2.push(Math.floor((Math.random()*12)+1));
}
//calculating answers
if (operator[i] == '+'){
answers.push(operand1[i] + operand2[i]);
} else if (operator[i] == '-'){
answers.push(operand1[i] - operand2[i]);
} else if (operator[i] == 'x'){
answers.push(operand1[i] * operand2[i]);
} else if (operator[i] == '\xF7'){
answers.push(operand1[i] / operand2[i]);
}
}
}
function runtest(number){
$('#question').append('' + operand1[iteration] + ' ' + operator[iteration] + ' ' + operand2[iteration] + ' = ');
$('#answer').keyup(function() {
if ($('#answer').val() == answers[iteration]){
finish = Date.now();
times.push(finish-start);
console.log(finish-start)
if(iteration == 0){
start = Date.now();
$('#runner').runner('start');
$('#counter').html(iteration);
};
iteration++;
correct(number);
}
});
}
function percentile(score){
$.ajax({
url: 'percentile.php',
data: {score: score},
type: 'post',
success: function(data){
$('#percentile').html('You beat <b>'+ data +'% </b>of people.');
}
});
}
function correct(number){
if(iteration == number){
$('#runner').runner('stop');
$('#runner').append('s');
time = parseInt($('#runner').html()) / (number - 1);
$('#runner').prepend('Total time: ');
$('body').append('Time per question: ' + time + 's');
stoptest();
} else {
$('#question').empty();
$('#counter').html(iteration);
$('#answer').val('');
$('#question').append('' + operand1[iteration] + ' ' + operator[iteration] + ' ' + operand2[iteration] + ' = ');
start = Date.now();
}
}
function stoptest(){
operand1 = [];
operand2 = [];
answers = [];
operator = [];
$('#question').remove();
$('#answer').remove();
console.log(times);
}
function gethighscore(id){
$.ajax({
async: false,
url: 'gethighscore.php',
data: {id: id},
type: 'post',
success: function(data){
friendscores.push(data);
console.log(data);
}
});
}
function getuserhighscore(id){
$.ajax({
async: false,
url: 'gethighscore.php',
data: {id: id},
type: 'post',
success: function(data){
user['highscore'] = data;
}
});
}
function userpercentile(score){
$.ajax({
url: 'percentile.php',
async: false,
data: {score: score},
type: 'post',
success: function(data){
user['percentile'] = data;
}
});
}
function post(name,score,unique){
$.ajax({
url: 'post.php',
data: {name: name, score: score, unique: unique},
type: 'post',
success: function(data){
$('#main').html('');
$('#main').append('<br><br><br><br><span id="message">Submitted! ok now try again</span><br><br>');
$('#main').append('<div id="restart">restart</div>');
}
});
}
function logg(score,unique,fb){
console.log('attempting to log');
$.ajax({
url: 'log.php',
data: {score: score, unique: unique, fb: fb},
type: 'post',
success: function(data){
console.log(data);
}
});
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function portrait(){
console.log('success');
}
$(document).ready(function(){
$.ajax({
url: 'total.php',
data: {},
type: 'post',
dataType: 'html',
success: function(data){
console.log(data);
$('.total').append('<b>'+numberWithCommas(data)+'</b>');
}
});
$('#form').hide();
$('#runner').runner({
countdown: true,
startAt: 30 * 1000,
stopAt: 0
}).on('runnerFinish', function(eventObject, info) {
times[0] = 0;
times[times.length - 1] = 0;
if(times[2] == times[3] == times[4] == times[5]){
window.location.replace("http://en.wikipedia.org/wiki/Hacker_(computer_security)");
}
unique = 15*iteration + 4;
percentile(iteration);
logg(iteration,unique,fbid);
var slowesttime = Math.max.apply(Math,times);
var position = times.indexOf(slowesttime);
var slowestq = '' + operand1[position] + ' ' + operator[position] + ' ' + operand2[position] + '';
var slowesta = answers[position];
$('#counter, #solidus, #runner').remove();
$('body').animate({backgroundColor: '#f0f0f0'});
$('#wrapper').fadeIn("fast");
if(fbconnect == true){
$('#sidebar').fadeIn("fast");
}
$('#score').append('<div id="results1">Total: <b>' + iteration + '</b></div>');
$('#score').append('<div id="percentile"></div>');
$('#score').append('<div id="other">Time per question: <b>' + (30/iteration).toFixed(2) + 's</b></div>');
$('#score').append('<div id="other">For future reference, <b>' + slowestq + ' = ' + slowesta + '</b>. It should not take <b>' + (slowesttime/1000).toFixed(2) + 's</b> to solve that next time. </div>');
$('#form').show();
$('#tweet').click(function(){
window.open('https://twitter.com/intent/tweet?text=omg+i+just+did+'+iteration+'+maths+problems+in+30s!+try+and+beat+me!&hashtags=speedsums&url=http%3A%2F%2Fwww.speedsums.com', 'Tweet', "height=300,width=500");
});
stoptest();
});
generateproblems(120);
runtest(120);
$('#answer').focus(function(){
$('body').animate({backgroundColor: '#BDC3C7'});
$('#wrapper').fadeOut("fast");
$('#instructions').fadeOut("fast");
$('#sidebar').fadeOut("fast");
});
$('#answer').blur(function(){
$('#wrapper').fadeIn("fast");
$('#instructions').fadeIn("fast");
if(fbconnect == true){
$('#sidebar').fadeIn("fast");
}
$('body').animate({backgroundColor: '#f0f0f0'});
});
$('#post').click(function(){
name = $('#name').val();
unique = 15*iteration + 4;
post(name,iteration,unique);
});
$('body').on('click','#restart, #retry', function() {
window.location.href = "index.html";
});
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
var ctx2 = $("#userchart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var userchart = new Chart(ctx2);
$.ajax({
url: 'distribution.php',
data: {},
type: 'get',
dataType:"json",
success: function(data22){
var dataarray = new Array();
for (var i=0;i<46;i++) {
dataarray.push(data22[i]);
}
data2 = {
labels : ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42"],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : dataarray
}
]
}
var options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
}
myLine = new Chart(document.getElementById("myChart").getContext("2d")).Bar(data2,options);
}
});
});
</script>
</head>
<body>
<div id="fb-root"></div>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.<span class="total">Total sums done: </span> -->
<div id="header"><div class="page"><a class="nav1">TEST</a><div id="logo"></div><a class="nav2">PRACTICE</a><div id="thumbnail"><div class="fb-login-button" id="fbloginbutton" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div></div></div></div><div id="sidebar" style="display:none"><h2>FRIENDS</h2><div id="friendcontainer"></div><div id="statscontainer"><h2>YOUR STATS</h2></div><canvas id="userchart" width="250" height="200"></canvas></div>
<div id="notice">Speedsums is under renovation - there's gonna be a bunch of cool new stuff soon, so keep checking back! -Taimur</a></div>
<br><div class="instructions"><span id="instructions">Click inside the box below to begin</span></div><div id="spacer"></div>
<div id="main">
<div id="question"></div><br>
<div><input id="answer" type="text" autocomplete="off"></div><br>
<div id="runner"></div><span id="solidus">/</span><div id="counter">0</div>
<div id="score"></div>
<div id="form">
<div id="tweet">Tweet Score</div><br>
<div id="retry">Retry</div>
</div><br><br>
</div>
<canvas id="myChart" width="1440" ></canvas>
<script>
// Include the UserVoice JavaScript SDK (only needed once on a page)
UserVoice=window.UserVoice||[];(function(){var uv=document.createElement('script');uv.type='text/javascript';uv.async=true;uv.src='//widget.uservoice.com/aIRVe5TPDRSYNkW7H1CAg.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(uv,s)})();
//
// UserVoice Javascript SDK developer documentation:
// https://www.uservoice.com/o/javascript-sdk
//
// Set colors
UserVoice.push(['set', {
accent_color: '#448dd6',
trigger_color: 'white',
trigger_background_color: '#448dd6'
}]);
// Identify the user and pass traits
// To enable, replace sample data with actual user traits and uncomment the line
UserVoice.push(['identify', {
//email: 'john.doe@example.com', // User’s email address
//name: 'John Doe', // User’s real name
//created_at: 1364406966, // Unix timestamp for the date the user signed up
//id: 123, // Optional: Unique id of the user (if set, this should not change)
//type: 'Owner', // Optional: segment your users by type
//account: {
// id: 123, // Optional: associate multiple users with a single account
// name: 'Acme, Co.', // Account name
// created_at: 1364406966, // Unix timestamp for the date the account was created
// monthly_rate: 9.99, // Decimal; monthly rate of the account
// ltv: 1495.00, // Decimal; lifetime value of the account
// plan: 'Enhanced' // Plan name for the account
//}
}]);
// Add default trigger to the bottom-right corner of the window:
UserVoice.push(['addTrigger', { mode: 'satisfaction', trigger_position: 'top-left' }]);
// Or, use your own custom trigger:
//UserVoice.push(['addTrigger', '#id', { mode: 'satisfaction' }]);
// Autoprompt for Satisfaction and SmartVote (only displayed under certain conditions)
UserVoice.push(['autoprompt', {}]);
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '219892158204692',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
if(fbconnect == true){
} else {
fbconnect = true;
$('#fbloginbutton').hide();
$('#friendcontainer').append('<span id="loader"><center>Loading...</center></span>');
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
FB.api(
"/me",
function (response) {
if (response && !response.error) {
fbid = response['id'];
user['id'] = response['id'];
getuserhighscore(user['id']);
userpercentile(parseInt(user['highscore']));
$('#statscontainer').append('<span class="label">Highest Score</span>: '+user['highscore']+'<br>');
$('#statscontainer').append('<span class="label">Percentile (global)</span>: '+user['percentile']+'<br>');
drawuserchart(user['id']);
}
}
);
FB.api(
"/fql?q=select%20uid%2C%20first_name%2C%20is_app_user%20from%20user%20where%20uid%20in%20(select%20uid2%20from%20friend%20where%20uid1%3Dme())%20and%20is_app_user%3D1",
function (response) {
console.log('friends installed:');
console.log(response);
console.log(response['data'][0].id);
var responseArray = [];
responseArray.push(response);
console.log(responseArray);
user['friends'] = response['data'].length;
if (response && !response.error) {
for (var i=0;i<response['data'].length;i++){
friend = response['data'][i];
console.log('friend coming up');
console.log(friend);
friends.push(friend.uid);
$('#friendcontainer').append('<div class="friendbox" id="'+friend.uid+'"></div>');
$('#'+friend.uid+'').append('<img class="friendpic" src="https://graph.facebook.com/'+friend.uid+'/picture?height=60&width=60&type=square">');
$('#'+friend.uid+'').append('<div class="friendname">'+friend.first_name+'</div>');
gethighscore(friend.uid);
$('#'+friend.uid+'').append(' - '+friendscores[i]+'');
console.log(friendscores);
}
$('#loader').remove();
user['friendrank'] = 1;
for (var i=0;i<friendscores.length;i++){
if(friendscores[i] > user['highscore']){
user['friendrank']++;
}
}
$('#statscontainer').append('<span class="label">Rank (among friends)</span>: '+user['friendrank']+'<br>');
} else {
console.log(response.error)
}
}
);
console.log(friends);
console.log(user)
FB.api(
"/me/picture",
{
"redirect": false,
"height": "100",
"type": "normal",
"width": "100"
},
function (response) {
if (response && !response.error) {
user['picture'] = response['data']['url'];
console.log(user['picture']);
$('#thumbnail').append('<img id="thumbnailpic" src="'+user['picture']+'">');
}
}
);
}
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
$('#sidebar').slideDown("slow");
});
}
</script>
</body>
</html>
快速算术-快速做数学
(函数(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]| |函数(){
(i[r].q=i[r].q | |[]).push(参数)},i[r].l=1*新日期();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(窗口,文档,“脚本”,“www.google-analytics.com/analytics.js”,“ga”);
ga(“创建”、“UA-46469577-1”、“speedsums.com”);
ga(‘发送’、‘页面浏览’);
css材料
var数据2;
var jsonn;
麦林变种;
var-fbid;var-fbid=0;
变量运算符=['+','-','x','\xF7'];
变量属性={
边框颜色:“绿色”,
边框宽度:“3px”,
高度:'37px'
};
var user={};
var-friends=[];
var friendscores=[];
var-friendpics=[];
无功连接;
变量操作数1;
变量操作数2;
var算子;
var答案;
var时间;
变量名;
变量一;
var-2;
var迭代=0;
var唯一性;
var时间=[];
var启动;
var整理;
函数drawuserchart(id){
log('drawuserchart()已初始化');
$.ajax({
url:'userchart.php',
数据:{id:id},
键入:“post”,
数据类型:“json”,
成功:功能(数据22){
console.log(data22);
var labelarray=新数组();
对于(var i=0;i嗯,至少我在代码中注意到两件事:
从我的角度来看,testAPI()的调用是不必要的,而且是“断章取义的”
如果将第一个API调用与第三个API调用组合在一起,则至少可以保存一个API调用
api('/me?fields=id,picture',函数{…})