This response is just a complement to the @hugocsl response .
When it comes to events like scroll
, resize
or mousemove
it is always important to remember that they are launched several times per second while the user interacts with the page. That is, depending on what you do within the handler function of the event, you can slow your page (eg accessing the DOM).
If there is no need to run this function so repeatedly you can use the techniques debounce
and throttle
, which serve to limit the execution of a function over a period of time.
debounce
will wait for the event to stop. to be released for X seconds before activating the handler function.
throttle
will only allow the function handler runs every X seconds.
Example:
// Só vai executar quando o usuário para de digitar por 1 segundo
$elemento.on('keyup', _.debounce(function() {
console.log('debounce');
}, 1000));
// Enquanto o usuário seguir digitando, vai executar a cada segundo
$elemento.on('keyup', _.throttle(function() {
console.log('throttle');
}, 1000));
Another, much simpler, optimization is to save the DOM element to a variable for later use, since access to the DOM is costly in terms of performance.
Instead of:
$(window).scroll(function() {
// é executado cada vez que 'scroll' é lançado
$("#brand-image").fadeOut();
});
It's more performative to use:
// É executado apenas uma vez
var $brandImage = $("#brand-image");
$(window).scroll(function() {
// Usa a refêrencia salva anteriormente
$brandImage.fadeOut();
});
And the last and least shocking is that when you do:
$(window).scrollTop()
You are converting a DOMElement to a jQuery object, it is not as costly as accessing the DOM, but it can still be easily replaced by the window.pageYOffset
" which is native and compatibility is acceptable (IE 9+).
Below is the @hugocsl code with the normal handler handler and throttle to illustrate the importance of these techniques.
PS: In the examples I'm using the methods _.debounce()
and _.throttle()
of the library lodash .
Normal
var $brandImage = $("#brand-image");
var $scrollHelper = $("#scroll-helper");
var count_scroll = 0;
$(window).scroll(function() {
$scrollHelper.html("scroll triggered: " + ++count_scroll);
if (this.pageYOffset >= 140) { // 140 é a distancia que vc rola antes da logo sumir
$brandImage.fadeOut();
} else {
$brandImage.fadeIn();
}
});
#scroll-helper {
position: fixed;
top: 80px;
left: 10px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
<a class="navbar-brand" href="#">
<img id="brand-image"src="https://placecage.com/50/50"/></a><buttonclass="navbar-toggler">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
<div style="height:1000px; width: 100ps;"></div>
<span id="scroll-helper">scroll triggered: 0</span>
Debounce
var $brandImage = $("#brand-image");
var $scrollHelper = $("#scroll-helper");
var count_scroll = 0;
$(window).scroll(_.debounce(function() {
$scrollHelper.html("scroll triggered: " + ++count_scroll);
if (this.pageYOffset >= 140) { // 140 é a distancia que vc rola antes da logo sumir
$brandImage.fadeOut();
} else {
$brandImage.fadeIn();
}
}, 300));
#scroll-helper {
position: fixed;
top: 80px;
left: 10px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script><navclass="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
<a class="navbar-brand" href="#">
<img id="brand-image"src="https://placecage.com/50/50"/></a><buttonclass="navbar-toggler">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
<div style="height:1000px; width: 100ps;"></div>
<span id="scroll-helper">scroll triggered: 0</span>
Throttle
var $brandImage = $("#brand-image");
var $scrollHelper = $("#scroll-helper");
var count_scroll = 0;
$(window).scroll(_.throttle(function() {
$scrollHelper.html("scroll triggered: " + ++count_scroll);
if (this.pageYOffset >= 140) { // 140 é a distancia que vc rola antes da logo sumir
$brandImage.fadeOut();
} else {
$brandImage.fadeIn();
}
}, 300));
#scroll-helper {
position: fixed;
top: 80px;
left: 10px;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script><navclass="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
<a class="navbar-brand" href="#">
<img id="brand-image"src="https://placecage.com/50/50"/></a><buttonclass="navbar-toggler">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
<div style="height:1000px; width: 100ps;"></div>
<span id="scroll-helper">scroll triggered: 0</span>