Created
March 12, 2020 06:25
-
-
Save yuriks2000/5508a3b57bff49bf3306fc4a9f0fc2ab to your computer and use it in GitHub Desktop.
Optimization of loading Yandex.Maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Переменная для включения/отключения индикатора загрузки | |
var spinner = $('.ymap-container').children('.loader'); | |
//Переменная для определения была ли хоть раз загружена Яндекс.Карта (чтобы избежать повторной загрузки при наведении) | |
var check_if_load = false; | |
//Необходимые переменные для того, чтобы задать координаты на Яндекс.Карте | |
var myMapTemp, myPlacemarkTemp; | |
//Функция создания карты сайта и затем вставки ее в блок с идентификатором "map-yandex" | |
function init () { | |
var myMapTemp = new ymaps.Map("map-yandex", { | |
center: [53.676730, 23.766629], // координаты центра на карте | |
zoom: 12, // коэффициент приближения карты | |
controls: ['zoomControl', 'fullscreenControl'] // выбираем только те функции, которые необходимы при использовании | |
}); | |
var myPlacemarkTemp = new ymaps.GeoObject({ | |
geometry: { | |
type: "Point", | |
coordinates: [53.676730, 23.766629] // координаты, где будет размещаться флажок на карте | |
} | |
}); | |
myMapTemp.geoObjects.add(myPlacemarkTemp); // помещаем флажок на карту | |
// Получаем первый экземпляр коллекции слоев, потом первый слой коллекции | |
var layer = myMapTemp.layers.get(0).get(0); | |
// Решение по callback-у для определения полной загрузки карты | |
waitForTilesLoad(layer).then(function() { | |
// Скрываем индикатор загрузки после полной загрузки карты | |
spinner.removeClass('is-active'); | |
}); | |
} | |
// Функция для определения полной загрузки карты (на самом деле проверяется загрузка тайлов) | |
function waitForTilesLoad(layer) { | |
return new ymaps.vow.Promise(function (resolve, reject) { | |
var tc = getTileContainer(layer), readyAll = true; | |
tc.tiles.each(function (tile, number) { | |
if (!tile.isReady()) { | |
readyAll = false; | |
} | |
}); | |
if (readyAll) { | |
resolve(); | |
} else { | |
tc.events.once("ready", function() { | |
resolve(); | |
}); | |
} | |
}); | |
} | |
function getTileContainer(layer) { | |
for (var k in layer) { | |
if (layer.hasOwnProperty(k)) { | |
if ( | |
layer[k] instanceof ymaps.layer.tileContainer.CanvasContainer | |
|| layer[k] instanceof ymaps.layer.tileContainer.DomContainer | |
) { | |
return layer[k]; | |
} | |
} | |
} | |
return null; | |
} | |
// Функция загрузки API Яндекс.Карт по требованию (в нашем случае при наведении) | |
function loadScript(url, callback){ | |
var script = document.createElement("script"); | |
if (script.readyState){ // IE | |
script.onreadystatechange = function(){ | |
if (script.readyState == "loaded" || | |
script.readyState == "complete"){ | |
script.onreadystatechange = null; | |
callback(); | |
} | |
}; | |
} else { // Другие браузеры | |
script.onload = function(){ | |
callback(); | |
}; | |
} | |
script.src = url; | |
document.getElementsByTagName("head")[0].appendChild(script); | |
} | |
// Основная функция, которая проверяет когда мы навели на блок с классом "ymap-container" | |
var ymap = function() { | |
$('.ymap-container').mouseenter(function(){ | |
if (!check_if_load) { // проверяем первый ли раз загружается Яндекс.Карта, если да, то загружаем | |
// Чтобы не было повторной загрузки карты, мы изменяем значение переменной | |
check_if_load = true; | |
// Показываем индикатор загрузки до тех пор, пока карта не загрузится | |
spinner.addClass('is-active'); | |
// Загружаем API Яндекс.Карт | |
loadScript("https://api-maps.yandex.ru/2.1/?lang=ru_RU&loadByRequire=1", function(){ | |
// Как только API Яндекс.Карт загрузились, сразу формируем карту и помещаем в блок с идентификатором "map-yandex" | |
ymaps.load(init); | |
}); | |
} | |
} | |
); | |
}; | |
$(function () { | |
ymap(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="ymap-container"> | |
<div class="loader loader-default"></div> | |
<div id="map-yandex"></div> | |
</div><!-- .ymap-container --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.ymap-container { | |
position: relative; | |
margin: 3em 0 2em 0; | |
overflow: hidden; | |
cursor: pointer; | |
background: url('../img/content/map.png') #ffffff no-repeat; | |
background-position: center center; | |
background-size: cover; | |
box-shadow: 0 0 2em 0 rgba(0,0,0,.2); | |
} | |
/* Блок, в котором появится Яндекс.Карта */ | |
#map-yandex { | |
position: relative; | |
z-index: 7; | |
width: 100%; | |
height: 20em; | |
cursor: pointer; | |
background-color: transparent; | |
} | |
.loader { | |
position: absolute; | |
z-index: 15; | |
top: -100%; | |
left: 0; | |
box-sizing: border-box; | |
width: 100%; | |
height: 100%; | |
overflow: hidden; | |
color: #000000; | |
transition: opacity .7s ease; | |
opacity: 0; | |
background-color: rgba(0,0,0,.55); | |
} | |
.loader:after, | |
.loader:before { | |
box-sizing: border-box; | |
} | |
.loader.is-active { | |
top: 0; | |
opacity: 1; | |
z-index: 5; | |
} | |
.loader-default:after { | |
position: absolute; | |
top: calc(50% - 24px); | |
left: calc(50% - 24px); | |
width: 48px; | |
height: 48px; | |
content: ''; | |
animation: rotation 1s linear infinite; | |
border: solid 8px #ffffff; | |
border-left-color: transparent; | |
border-radius: 50%; | |
} | |
@keyframes rotation { | |
from { | |
transform: rotate(0); | |
} | |
to { | |
transform: rotate(359deg); | |
} | |
} | |
@keyframes blink { | |
from { | |
opacity: .5; | |
} | |
to { | |
opacity: 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment