ready demo

.ready( handler )

Выполняет функцию, как только DOM полностью загрузился.

version added: 1.0 .ready( handler )

С помощью стандартных средств javascript, вы можете обработать событие onload, которое выстреливает после готовности страницы. Однако, оно будет вызвано только после того, как будет сформирована вся страница, включая все картинки и другие мультимедийные элементы. Событие ready выстреливает в момент готовности DOM, что происходит раньше начала загрузки мультимедийных файлов. Это прекрасный момент, когда можно приступить к установке обработчиков различных событий и выполнять другой JavaScript код.

Если же ваш код базируется, к примеру, на каких-то размерах изображений, то его необходимо поместить в дополнительный обработчик.

Данные 3 записи эквивалентны:

$(document).ready(handler) $().ready(handler) (не рекомендуется) $(handler)

Метод .ready() может быть вызван только от объекта текущего документа, так что селектор можно опустить.

Обычно в метод .ready() передают анонимную функцию:

Алиас на пространство имён jQuery

Если вы используете одновременно какую-то другую JavaScript библиотеку, то вызовите метод $.noConflict() для избежании коллизий. На самом деле $ является сокращением для слова jQuery. Однако, метод .ready() принимает аргумент, где мы можем указать этот знак. Это значит, что мы можем сами переименовать объект:

jQuery(document).ready(function($) < // код с префиксом $ >);

Пример

Отобразить сообщение после готовности DOM-а.

     p    

Not 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()

                  ТОП-10 Хостеров:

                  Шпаргалки:

                  Получать новые уроки на E-mail:

                  RSS подписка

                  Авторизация

                  Рекомендуем

                  © 2023 Евгений Попов. Все права защищены. Служба поддержки
                  Сайт мониторится с помощью сервиса ping-admin
                  🙂

                  Источник

                  $( document ).ready()

                  A page can’t be manipulated safely until the document is «ready.» jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( «load», function() < . >) will run once the entire page (images or iframes), not just the DOM, is ready.

                  // A $( document ).ready() block.
                  $( document ).ready(function( )
                  console.log( "ready!" );
                  >);

                  Experienced developers sometimes use the shorthand $() for $( document ).ready() . If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form.

                  // Shorthand for $( document ).ready()
                  $(function( )
                  console.log( "ready!" );
                  >);

                  You can also pass a named function to $( document ).ready() instead of passing an anonymous function.

                  // Passing a named function instead of an anonymous function.
                  function readyFn( jQuery )
                  // Code to run when the document is ready.
                  >
                  $( document ).ready( readyFn );
                  // or:
                  $( window ).on( "load", readyFn );

                  The example below shows $( document ).ready() and $( window ).on( "load" ) in action. The code tries to load a website URL in an and checks for both events:

                  html>
                  head>
                  script src="https://code.jquery.com/jquery-1.9.1.min.js"> script>
                  script>
                  $( document ).ready(function( )
                  console.log( "document loaded" );
                  >);
                  $( window ).on( "load", function( )
                  console.log( "window loaded" );
                  >);
                  script>
                  head>
                  body>
                  iframe src="http://techcrunch.com"> iframe>
                  body>
                  html>

                  Last Updated

                  Suggestions, Problems, Feedback?

                  Chapters

                  Books

                  Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

                  Источник

                  .ready()

                  Description: Specify a function to execute when the DOM is fully loaded.

                  version added: 1.0 .ready( handler )

                  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.
                  >);

                  Источник

                  Читайте также:  Заголовок
Оцените статью