.ready( handler )
Выполняет функцию, как только DOM полностью загрузился.
version added: 1.0 .ready( handler )
С помощью стандартных средств javascript, вы можете обработать событие onload, которое выстреливает после готовности страницы. Однако, оно будет вызвано только после того, как будет сформирована вся страница, включая все картинки и другие мультимедийные элементы. Событие ready выстреливает в момент готовности DOM, что происходит раньше начала загрузки мультимедийных файлов. Это прекрасный момент, когда можно приступить к установке обработчиков различных событий и выполнять другой JavaScript код.
Если же ваш код базируется, к примеру, на каких-то размерах изображений, то его необходимо поместить в дополнительный обработчик.
Данные 3 записи эквивалентны:
$(document).ready(handler) $().ready(handler) (не рекомендуется) $(handler)
Метод .ready() может быть вызван только от объекта текущего документа, так что селектор можно опустить.
Обычно в метод .ready() передают анонимную функцию:
$(document).ready(function() < // Обработчик для .ready() >);
$(function() < // Обработчик для .ready() >);
Алиас на пространство имён jQuery
Если вы используете одновременно какую-то другую JavaScript библиотеку, то вызовите метод $.noConflict() для избежании коллизий. На самом деле $ является сокращением для слова jQuery. Однако, метод .ready() принимает аргумент, где мы можем указать этот знак. Это значит, что мы можем сами переименовать объект:
jQuery(document).ready(function($) < // код с префиксом $ >);
Пример
Отобразить сообщение после готовности DOM-а.
ready demo pNot loaded yet.
Шпаргалка jQuery:
- Ajax
- Global Ajax Event Handlers
- .ajaxComplete()
- :button
- :checkbox
- :checked
- :disabled
- :enabled
- :file
- :focus
- :image
- .serializeArray()
- .serialize()
- jQuery.param()
- jQuery.ajax()
- jQuery.ajaxSetup()
- jQuery.ajaxPrefilter()
- jQuery.ajaxTransport()
- jQuery.get()
- jQuery.post()
- .load()
- jQuery.getJSON()
- jQuery.getScript()
- .serialize()
- .serializeArray()
- jQuery.param()
- .val()
- .blur()
- .change()
- .focus()
- .addClass()
- .hasClass()
- .removeClass()
- .toggleClass()
- .html()
- .removeAttr()
- .prop()
- .removeProp()
- .attr()
- .val()
- Collection Manipulation
- jQuery.param()
- .data()
- .removeData()
- Class Attribute
- .addClass()
- .hasClass()
- .removeClass()
- .toggleClass()
- .clone()
- .wrap()
- .wrapAll()
- .wrapInner()
- .unwrap()
- .append()
- .appendTo()
- .html()
- .text()
- .prepend()
- .prependTo()
- .after()
- .before()
- .insertAfter()
- .insertBefore()
- .unwrap()
- .remove()
- .empty()
- .detach()
- .replaceAll()
- .replaceWith()
- .removeProp()
- .removeAttr()
- .prop()
- .attr()
- .val()
- .css()
- .height()
- .width()
- .innerHeight()
- .innerWidth()
- .outerHeight()
- .outerWidth()
- .offset()
- .position()
- .scrollLeft()
- .scrollTop()
- .height()
- .width()
- .innerHeight()
- .innerWidth()
- .outerHeight()
- .outerWidth()
- jQuery.holdReady()
- jQuery()
- jQuery.noConflict()
- jQuery.when()
- .addClass()
- .hasClass()
- .removeClass()
- .toggleClass()
- .css()
- .height()
- .width()
- .innerHeight()
- .innerWidth()
- .outerHeight()
- .outerWidth()
- .offset()
- .position()
- .scrollLeft()
- .scrollTop()
- .clearQueue()
- .dequeue()
- .data()
- jQuery.hasData()
- jQuery.removeData()
- jQuery.dequeue()
- .removeData()
- jQuery.data()
- .queue()
- Custom
- .clearQueue()
- .dequeue()
- .queue()
- .clearQueue()
- .dequeue()
- jQuery.dequeue()
- jQuery.data()
- .queue()
- jQuery.proxy()
- callbacks.add()
- callbacks.disable()
- callbacks.disabled()
- callbacks.empty()
- callbacks.fire()
- callbacks.fired()
- callbacks.fireWith()
- callbacks.has()
- callbacks.lock()
- callbacks.locked()
- callbacks.remove()
- jQuery.Callbacks()
- deferred.always()
- deferred.done()
- deferred.fail()
- deferred.notify()
- deferred.notifyWith()
- deferred.progress()
- deferred.promise()
- deferred.reject()
- deferred.rejectWith()
- deferred.resolve()
- deferred.resolveWith()
- deferred.state()
- deferred.then()
- Basics
- Универсальный селектор (“*”)
- jQuery( «.class» )
- Селектор элементов (“element”)
- Селектор ID (“#id”)
- Множественный (“selector1, selector2, selectorN”)
- Селектор по префиксу [name|=”value”]
- Селектор содержащий значение [name*=»value»]
- Селектор, содержащий слово [name~=»value»]
- Селектор по атрибуту, на конце которого [name$=»value»]
- Селектор по равенству [name=»value»]
- Селектор по неравенству [name!=»value»]
- Значение атрибута начинается с [name^=»value»]
- Селектор по наличию атрибута [name]
- Множественный селектор по атрибуту [name=»value»][name2=»value2″]
- :animated Selector
- :eq()
- :even
- :first
- :focus
- :gt()
- :header
- :lang()
- :last
- :lt()
- :first-child
- :first-of-type
- :last-child
- :last-of-type
- :nth-child()
- :nth-last-child()
- :nth-last-of-type()
- :nth-of-type()
- :only-child
- :only-of-type
- :contains()
- :empty
- :has()
- :parent
- Browser Events
- .resize()
- .scroll()
- .ready()
- .bind()
- .delegate()
- jQuery.proxy()
- .off()
- .one()
- .trigger()
- .triggerHandler()
- .unbind()
- .undelegate()
- event.currentTarget
- event.data
- event.delegateTarget
- event.isDefaultPrevented()
- event.isImmediatePropagationStopped()
- event.isPropagationStopped()
- event.metaKey
- event.namespace
- event.pageX
- event.pageY
- event.preventDefault()
- event.relatedTarget
- event.result
- event.stopImmediatePropagation()
- event.stopPropagation()
- event.target
- event.timeStamp
- event.type
- event.which
- .blur()
- .change()
- .focus()
- .focusin()
Что такое $(document).ready(function ()?
Я всегда думал, что строка $(document).ready(function () — ждет загрузки DOM, но оказалось, что она делает что-то ещё
Потому что у меня есть файлы со скриптами и файл со slick.slider. Если я подключаю слик в самом низу то он почему то работает хотя функции для его вызова описаны выше. А если я убираю $(document).ready(function (), то слик не работаетЧто делает $(document).ready(function () ?
script(src="https://qna.habr.com/q/build/js/jquery.js") script(src="https://qna.habr.com/q/build/js/main.js") script(src="https://qna.habr.com/q/build/js/main2.js") script(src="https://qna.habr.com/q/build/js/slick.min.js")
- Вопрос задан более двух лет назад
- 867 просмотров
Комментировать
Решения вопроса 1Страницей нельзя безопасно манипулировать, пока документ не «$(document).ready». Код, в $(document) .ready (), будет запущен только после того, как объектная модель документа (DOM) страницы будет готова для выполнения кода JavaScript.
=> слик не работает т.к. ему ещё не с чем работать
Ответ написан более двух лет назад
Комментировать
Нравится Комментировать
Ответы на вопрос 0
Ваш ответ на вопросВойдите, чтобы написать ответ
- HTML
- +1 ещё
Как стилизовать данный элемент?
- 1 подписчик
- 8 часов назад
- 37 просмотров
.ready()
Description: Specify a function to execute when the DOM is fully loaded.
version added: 1.0 .ready( handler )
handler
A function to execute after the DOM is ready.The .ready() method offers a way to run JavaScript code as soon as the page’s Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins. When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added. As of jQuery 3.0, jQuery ensures that an exception occuring in one handler does not prevent subsequently added handlers from executing.
Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery’s .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ) , the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.
Browsers also provide the load event on the window object. When this event fires it indicates that all assets on the page have loaded, including images. This event can be watched in jQuery using $( window ).on( «load», handler ) . In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
Note that although the DOM always becomes ready before the page is fully loaded, it is usually not safe to attach a load event listener in code executed during a .ready() handler. For example, scripts can be loaded dynamically long after the page has loaded using methods such as $.getScript() . Although handlers added by .ready() will always be executed in a dynamically loaded script, the window ‘s load event has already occurred and those listeners will never run.
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
- $( handler )
- $( document ).ready( handler )
- $( «document» ).ready( handler )
- $( «img» ).ready( handler )
- $().ready( handler )
As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method’s behavior. For example, the third syntax works with «document» which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.
There is also $(document).on( «ready», handler ) , deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.
The .ready() method is typically used with an anonymous function:
$( document ).ready(function( )
// Handler for .ready() called.
>);
Событие ready
Как мы уже упоминали в предыдущих главах, привычка работать с готовым документом может сослужить хорошую службу в будущем. Тогда можно поставить ваш JavaScript код в самое начало документа, в секцию head, в виде готового кода или ссылки на внешний JavaScript файл. Вы можете поместить его в ивент ready внутри документа. Рассмотрим тот же самый пример из главы "Hello, world!", но в этот раз поместит код в ивент:
Смотрите, что мы делаем. Мы создаем функцию, называем ее DocumentReady, и она запускается в тот самый момент, когда документ готов для работы с DOM. В последней строчке кода мы используем ready() метод, чтобы назначить нашей функции ready ивент, т.е. сказать jQuery, что как только документ готов, мы хотим вызвать нашу функцию.
Однако мы можем немного упростить наш код, используя вместо этого анонимную функцию JavaScript. По сути, вместо называния функции, мы просто создаем ее и затем немедленно передаем ей ссылку на функцию ready(). Если вы новичок в JavaScript, вам, наверное, все это пока кажется слишком сложным, но когда вы привыкнете к языку, вы оцените, как можно добиться того же результата меньшими строчками кода:
Даже такой вариант показался слишком длинным команде jQuery, поэтому они решили создать версию (загрузчик) конструктора jQuery, который берет значение готовой функции как параметр, и на выходе получает:
В последнем примере, наша анонимная функция отправлена прямиком в jQuery конструктор, который назначает её ивенту ready. Когда вы протестируете код, вы увидите, что ивент начинает работать в момент загрузки страницы, т.е. так быстро, что вы даже не замечаете этого.
Как уже ясно, запаковывать ваш код в ready event function - лучшая практика при работе с jQuery, и поэтому мы будем часто использовать этот подход в течение всего курса, кроме случаев, когда нам надо будет уменьшить размер примера.
This article has been fully translated into the following languages:
Is your preferred language not on the list? Click here to help us translate this article into your language!
- .ajaxComplete()
- Global Ajax Event Handlers