jQuery resize(),scroll():使用变量的好习惯? [英] jQuery resize(), scroll(): good practice to use variables?

查看:88
本文介绍了jQuery resize(),scroll():使用变量的好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的网站在滚动时出现延迟.我只是想问一下,在$(window).scroll(function () {}中初始化所需的jQuery对象是否是一种好习惯?

So my website is experiencing lag when scrolling. I just wanted to ask if it's a good practice to initialize the jQuery objects that you need in $(window).scroll(function () {}?

例如:

$(window).scroll(function () {
  $thisContainer = $('.section #container');

  // 10 more initializations...
  $thisContainer.css(); // something like that...
}

我觉得这不是一个好主意,因为每次用户滚动时都会经常调用此函数.当调用它时,这些变量将被重新初始化.结果将浪费大量的内存和时间.

I feel like it wouldn't be a good idea since this function gets called really often every time the user scrolls. And when it is called, those variables would be reinitialized. That as a result would waste a whole lot of memory and time.

谢谢!

推荐答案

通常,您应该避免在由scroll事件触发的回调中执行任何操作,因为该回调将针对滚动窗口的每个像素执行.但是,根据您正在构建的应用程序,在该回调中根本无法避免某些事情.

In general you should avoid doing anything inside a callback that was fired by the scroll event because the callback will be executed for every pixel that the window is scrolled. However, depending on the application that you're building, some things simply cannot be avoided inside that callback.

在滚动回调中执行很多昂贵"的操作或查询会完全冻结浏览器,并使您的应用程序无法使用,因此您必须非常小心并谨慎操作.

Doing a lot of "expensive" manipulations or queries inside the scroll callback can totally freeze the browser and will make your application unusable, so you have to be very careful and performance cautious.

以下是一些良好做法的例子.

Here are some examples of good practices.

实时示例: http://jsfiddle.net/tfjyf0a3/

// Since we can get away with querying the elements outside of the callback 
// our application will be a lot snappier because we're doing less work for 
// every scrolled pixel. Always query DOM elements outside if possible.
var $output = $('#output');
var $window = $(window);

// This function is executed for every scrolled pixel, so we need to 
// avoid doing "expensive" queries or changing the DOM in here too.
function changeFontSize(scrollNumber) {
  // Setting the fontSize here is unavoidable because our application needs it. 
  $output.css('fontSize', scrollNumber <= 50 ? 18 : Math.floor(scrollNumber/10));
}

$window.on('scroll', function() {
  // Since `$(this)` here would be the window object, it's better to 
  // just use the previous reference named `$window`.
  // Querying the scrolled position here is unavoidable because our 
  // application needs it.
  var currentScroll = $window.scrollTop();

  // Saving a reference of the `scrollTop()` value is better when 
  // we need to re-use its value.
  $output.html(currentScroll + 'px');

  // We have to be cautious inside this function as well.
  changeFontSize(currentScroll);
});


// This is a good practice when you need to guarantee the execution of the function 
// when there isn't enough content in the body to cause a scrollbar in the Browser. 
// 
// The 'scroll' event will fire only when there is a scrollbar in the Browser.
$window.scroll();


有时,您需要在滚动的回调函数中执行昂贵的" DOM操作,查询甚至Ajax请求.例如,想象构建一个实现称为无限加载的模式的应用程序.在此应用程序中,当用户通过快速或缓慢滚动到达页面底部附近时,您将需要执行以下操作:


Sometimes you will need to do "expensive" DOM manipulations, queries, or even Ajax requests inside the scroll's callback function. For example imagine building an application that implements a pattern known as infinite loading. In this application when the user has reached close to the bottom of the page by scrolling quickly or slowly, you will need to do the following:

  1. 检查用户是否已滚动到底部.
  2. 检查是否有更多资源要加载.
  3. 加载资源.
  4. 将新资源添加到DOM.

您绝对不希望在每个滚动像素上执行上述所有步骤.在这种情况下,一种很好的做法是延迟上述步骤.一个示例可能看起来像这样:

You definitely wouldn't want to execute all the steps above on every scrolled pixel. A very good practice for this situation is to delay the steps above. An example might look like this:

实时示例: http://jsfiddle.net/35qb1b88/

var $output = $('#output');
var $window = $(window);
var timer;

function changeFontSize(scrollNumber) {
  $output.css('fontSize', scrollNumber <= 50 ? 18 : Math.floor(scrollNumber/10));

  // ...
  // load resources
  // append in DOM
  // ...etc
}

function scrollHandler() {
  var currentScroll = $window.scrollTop();

  $output.html(currentScroll + 'px');
  changeFontSize(currentScroll);
}

// This callback will be executed for every pixel but it will 
// do nothing if we're scrolling too fast because we're clearing
// the timeout. Only when scrolling has stopped and at least 100
// milliseconds have passed will the `scrollHandler` function run.
$window.on('scroll', function() {
  timer && window.clearTimeout(timer);
  timer = window.setTimeout(scrollHandler, 100);
});

$window.scroll();


相同的原则也适用于resize事件.


The same principles would apply for the resize event too.

这篇关于jQuery resize(),scroll():使用变量的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆