浏览器冻结几秒钟

时间:2011-10-14 16:16:35

标签: javascript

当以下代码运行时,它会使浏览器冻结几个秒。 我怎么能阻止这个?感谢

function rsfp_changePage(formId, page, totalPages, validate)
{
if (validate)
{
    var form = rsfp_getForm(formId);
    if (!ajaxValidation(form, page))
        return false;
}

for (var i=0; i<=totalPages; i++)
{
    var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
    if (thePage)
        document.getElementById('rsform_' + formId + '_page_' + i).style.display = 'none';
}

var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage)
{
    thePage.style.display = '';
    try {
        eval('if (typeof rsfp_showProgress_' + formId + ' == "function") rsfp_showProgress_' + formId + '(' + page + ')');
    }
    catch (err) { }
}
}

...

您会在http://www.ocsl.ch/dev找到该表单 用户名:stackoverflow / 密码:stackoverflow 先登录然后转到http://www.ocsl.ch/dev/sejour-linguistique/adultes/demande-d-offre-en-ligne 进入此页面后,单击绿色按钮“suivant”,您将看到它冻结了很少的意愿。 在内容下面是script.js文件,其中包含ajaxvalidation fonction。 希望有点帮助。请询问您是否需要其他可能有用的东西。

function refreshCaptcha(componentId, captchaPath)
{
if(!captchaPath) captchaPath = 'index.php?option=com_rsform&task=captcha&componentId=' + componentId;
document.getElementById('captcha' + componentId).src = captchaPath + '&' + Math.random();
document.getElementById('captchaTxt' + componentId).value='';
document.getElementById('captchaTxt' + componentId).focus();
}

function number_format(number, decimals, dec_point, thousands_sep)
{
var n = number, prec = decimals;
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 0 : Math.abs(prec);
var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
var dec = (typeof dec_point == "undefined") ? '.' : dec_point;

var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

var abs = Math.abs(n).toFixed(prec);
var _, i;

if (abs >= 1000) {
    _ = abs.split(/\D/);
    i = _[0].length % 3 || 3;

    _[0] = s.slice(0,i + (n < 0)) +
          _[0].slice(i).replace(/(\d{3})/g, sep+'$1');

    s = _.join(dec);
} else {
    s = s.replace('.', dec);
}

return s;
}

function buildXmlHttp()
{
var xmlHttp;
try
{
    xmlHttp=new XMLHttpRequest();
}
catch (e)
{
    try
    {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            alert("Your browser does not support AJAX!");
            return false;
        }
    }
}
return xmlHttp;
}

function ajaxValidation(form, page)
{
try
{
    var el = form.elements.length;
}
catch (err)
{
    form = this;
}

var xmlHttp = buildXmlHttp();
var url = 'index.php?option=com_rsform&task=ajaxValidate';

if (page)
    url += '&page=' + page;

var params = new Array();
var submits = new Array();
var success = false;
var formId = 0;
for (i=0; i<form.elements.length; i++)
{
    // don't send an empty value
    if (!form.elements[i].name) continue;
    if (form.elements[i].name.length == 0) continue;
    // check if the checkbox is checked
    if (form.elements[i].type == 'checkbox' && form.elements[i].checked == false) continue;
    // check if the radio is selected
    if (form.elements[i].type == 'radio' && form.elements[i].checked == false) continue;

    if (form.elements[i].type == 'submit')
    {
        submits.push(form.elements[i]);
        form.elements[i].disabled = true;
    }

    // check if form is a dropdown with multiple selections
    if (form.elements[i].type == 'select-multiple')
    {
        for (var j=0; j<form.elements[i].options.length; j++)
            if (form.elements[i].options[j].selected)
                params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].options[j].value));

        continue;
    }

    if (form.elements[i].name == 'form[formId]')
        formId = form.elements[i].value;

    params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value));
}

params = params.join('&');

xmlHttp.open("POST", url, false);

//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
var success = true;

if (xmlHttp.responseText.indexOf("\n") != -1)
{
    var response = xmlHttp.responseText.split("\n");
    // All spans set to no error
    var ids = response[0].split(',');
    for (var i=0; i<ids.length; i++)
        if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
            document.getElementById('component'+ids[i]).className = 'formNoError';

    // Show errors
    var ids = response[1].split(',');
    for (var i=0; i<ids.length; i++)
        if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
        {
            document.getElementById('component'+ids[i]).className = 'formError';
            success = false;
        }

    if (response.length == 4)
    {
        page = parseInt(response[2]) - 1;
        totalPages = parseInt(response[3]);
        rsfp_changePage(formId, page, totalPages, false);
    }

    for (var i=0; i<submits.length; i++)
        submits[i].disabled = false;
}

if (success == false && document.getElementById('rsform_error_' + formId))
{
    try {
        document.getElementById('rsform_error_' + formId).style.display = '';
    }
    catch (err) { }
}

return success;
}

function rsfp_addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}

function rsfp_getForm(formId)
{
var formIds = document.getElementsByName('form[formId]');
for (var i=0; i<formIds.length; i++)
{
    if (parseInt(formIds[i].value) != parseInt(formId))
        continue;

    var form = formIds[i].parentNode;       
    if (form.tagName == 'FORM' || form.nodeName == 'FORM')
        return form;

    while (form.parentNode)
    {
        form = form.parentNode;
        if (form.tagName == 'FORM' || form.nodeName == 'FORM')
            return form;
    }
}
}

谢谢@JuanMendes,遗憾的是没有帮助。我做了一些研究,以找出如何修改代码以发送异步请求,但我没有成功。在ajaxValidation函数中,有

xmlHttp.open("POST", url, false);

如果我将其更改为

xmlHttp.open("POST", url, true);

它应该是异步请求,不是吗。

当我测试它时,它没有冻结浏览器,但是如果表单上没有填写字段,它不会显示错误。相反,它验证了哪些不是意味着什么。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

正如提到的IAbstractDownvoteFactory,你可能在同步模式下调用ajax,这意味着,在等待网络调用时冻结屏幕。

它看起来那样的原因是你的ajaxValidation正在返回一个值。通常,您会发送异步请求,而ajaxValidation将进行回调。然后UI不会挂起等待XHR。

// This is an improvement over what you had
// Still poor code, since it's hard to tell what the function is doing
function rsfp_changePage(formId, page, totalPages, validate)
{
  var form = rsfp_getForm(formId);
  if (validate) {
    // Change your AJAX validation function to take a callback, which passes the return
    // value (asynchronous) instead of relying on a return value (synchronous)
    ajaxValidation(form, page, function(validationResult){
      if (validationResult) {
        showProgress();
      }
    });        
  } else {
    showProgress();
  }

  function showProgress() {
    for (var i=0; i<=totalPages; i++) {
      var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
      if (thePage) {
        thePage .style.display = 'none';
      }

      var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
      if (thePage) {
        thePage.style.display = '';
        // Don't use eval, use window and bracket to  avoid it
        var func = window["rsfp_showProgress_" + formId];
        if (typeof func  == "function") {
            func(page);
        }
      }
    }        
  }    
}