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: – Immediately after starting doInit(function(){...your code is here...}) – After downloading all content (DOMContentLoaded), that's the same as $(document).onReady() by jQuery, but of course, without jQuery. – After the final loading of all the elements of the page (scripts, pictures and other), analogue of $(window).load(function() by jQuery. Usage example: 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-код. Поможет подождать асинхронной загрузки каких-то внешних скриптов (или инициализации каких-то переменных), а затем выполнит код. Попытка инициализации происходит трижды: – Немедленно после запуска doInit(function(){...ваш код тут...}) – После загрузки всего контента (DOMContentLoaded), аналог $(document).onReady() от jQuery. Только конечно, без jQuery. – После окончательной загрузки всех элементов страницы (скриптов, картинок и прочего), аналог $(window).load(function() от jQuery. Пример использования: В этом примере мы ожидаем загрузки jQuery и какого-то ещё класса именованного jQuery.fn.someClass. Когда условие будет выполнено, всё на своих местах — запускается инициализация чего-то. ———————————— DoInit (copy-paste 129 bytes of code below and insert into 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 – 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() – 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 }) ———————————— Цей документ було скопійовано з FAVOR.com.ua (https://favor.com.ua/blogs/30122.html). Всі права на матеріал зберігаються за його автором. При перепублікуванні посилання на джерело матеріалу є обов’язковим! Дата документу: 16 серпня 2018 р.