Awaiting of asynchronous load and initialization of some JavaScript code / Ожидание асинхронной загрузки и инициализация какого-то JavaScript-кода
  
Author:

UPD 22.08.2018: code below is obsolete and was updated. See https://www.favor.com.ua/js/onready.js.


English:
This minimalistic JS-code (see "doInit" function below) will help timely initialize any other JS-code. It will help to wait for an asynchronous loading of some external scripts (or initialization of some variables), and then execute the code.

An initialization attempt occurs three times:

  1. Immediately after starting doInit(function(){...your code is here...})
  2. After downloading all content (DOMContentLoaded), that's the same as $(document).onReady() by jQuery, but of course, without jQuery.
  3. After the final loading of all the elements of the page (scripts, pictures and other), analogue of $(window).load(function() by jQuery.

Usage example:
<script>
// <![CDATA[
  doInit(function(){
  if (typeof jQuery=="undefined"||typeof jQuery.fn.someClass=="undefined") return 1 // wait some more till full load
  $("#mykeyelement").initMyElement()
})
// ]]>
</script>

In this example, we expect to load jQuery and some other class named jQuery.fn.someClass. When the condition is satisfied, everything in its place — it starts initialization of something.


По-русски:
Этот минималистичный JS-код (см. функцию "doInit" ниже) своевременно инициализирует любой другой JS-код. Поможет подождать асинхронной загрузки каких-то внешних скриптов (или инициализации каких-то переменных), а затем выполнит код.

Попытка инициализации происходит трижды:

  1. Немедленно после запуска doInit(function(){...ваш код тут...})
  2. После загрузки всего контента (DOMContentLoaded), аналог $(document).onReady() от jQuery. Только конечно, без jQuery.
  3. После окончательной загрузки всех элементов страницы (скриптов, картинок и прочего), аналог $(window).load(function() от jQuery.

Пример использования:
<script>
// <![CDATA[
  doInit(function(){
  if (typeof jQuery=="undefined"||typeof jQuery.fn.someClass=="undefined") return 1 // wait some more till full load
  $("#mykeyelement").initMyElement()
})
// ]]>
</script>

В этом примере мы ожидаем загрузки jQuery и какого-то ещё класса именованного jQuery.fn.someClass. Когда условие будет выполнено, всё на своих местах — запускается инициализация чего-то.


DoInit (copy-paste 129 bytes of code below and insert into <head> section of each of your HTML-page):

doInit=function(f){if(f()){document.addEventListener("DOMContentLoaded",function(){if(f()){window.addEventListener("load",f)}})}}

// UPD. Version 1.1. If we want to wait at least till the content loaded (document is ready)

doInit=function(f,l){if(l||f()){document.addEventListener("DOMContentLoaded",function(){if(f()){window.addEventListener("load",f)}})}}
 

// UPD. Version 1.2. make function above shorter on few bytes

doInit=function(f,l){(l||f())&&document.addEventListener("DOMContentLoaded",function(){f()&&window.addEventListener("load",f)})}

jqWait (another function, which wait for both jQuery AND some of our function, named and represented by string)

jqWait=function(n,f){doInit(function(){if("undefined"==typeof $||"function"!=typeof window[n])return 1;window[n]();if(f)f()})}

So we may

  1. Wrap all our jQuery modules (.js-files) into functions like:

    var async_jq_plugname = function() { /*plugname is just example, rename it to the name of jQuery-plugin*/
    (function($) {
             // code of the plugin
    })(jQuery)

    /*let's try to initialize module imediately on load. Check availability of jQuery, then execute initialization if jQuery is already loaded */
    if (typeof $!="undefined") async_jq_plugname()

     
  2. Additionally you may execute initialization in your HTML-page, after inlining the elements whose visiblity depends on jQuery module (which should be initialized when both jQuery and jQuery plugin will be loaded):

    jqWait('async_jq_plugname', function(){
       // some code which should be guaranteed to run for initialization

    })

 


Send by E-mailSend by E-mail   Print versionPrint version
Comments(0)

No comments yet… Be the first to leave comment on this topic!

or
You may sign in using:
Enter with Facebook Enter with Google Enter with VK