Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By RobLoach on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.0.x
Introduced in version:
8.0.0-beta8
Issue links:
Description:
jQuery Once now targets version 2.x. This update comes with some new features:
- Performance improvements through using jQuery's .data() rather than manipulating the DOM
- Moves towards jQuery chaining rather than function callbacks
- A new
.findOnce()
method to select elements that have already beenonce
'd.
Drupal 7
/**
* Attach my behavior to the .mybehavior elements.
*/
Drupal.behaviors.mybehavior = {
attach: function(context) {
// Set the initial state of the toolbar.
$('.mybehavior', context).once('mybehavior', function() {
// Do something to the elements.
$(this).css('background-color', 'red');
});
}
};
Drupal 8
/**
* Attach my behavior to the .mybehavior elements.
*/
Drupal.behaviors.mybehavior = {
attach: function(context) {
// Set the initial state of the toolbar.
$(context).find('[data-mybehavior]').once('mybehavior').each(function() {
// Do something to the elements.
$(this).css('background-color', 'red');
});
}
};
See more examples and information in the jQuery Once API.
Impacts:
Module developers
Comments
To me, it was not obvious
To me, it was not obvious right away what the change was so:
before
after
Also, previousely the value used for the once() method was used as class name and '-processed' was appended to is, so the example above would result in:
now it is just:
So in order to visually(browsing the source code) see if the script has run you need to attach the class(or any other indicator) manually. You can also try
and look for
jQueryOnceInit: true
but if you'd use the old code styleit would indicate the once() method has run but in fact the logic within the empty function() would not get executed.
If you have been using this code style:
then this change does not concern you(except the '-processed' class removal).
Another Once Example
Another thing to make sure is
Another thing to make sure is that your library has a dependency on
core/jquery.once
Alex Pott