[英]Lazy load Google map
我想延遲加載谷歌地圖以獲得更好的 SEO 頁面加載速度。 我的 javascript 工作正常,但它仍然嘗試多次加載 map。 我怎樣才能讓它加載一次? 我找到了其他腳本,但我想使用盡可能少的代碼。
我的腳本:
google = false;
$(window).scroll(function() {
var hT = $('#google-map').offset().top,
hH = $('#google-map').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
if (!google) $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
initialize();
});
}
});
控制台日志:
js?key={key}&_=1591085205888:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205888:140
js?key={key}&_=1591085205890:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205890:140
js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
提前致謝! 彼得
我認為您一遍又一遍地運行腳本? 在 if 語句后添加 google = true ?
google = false;
$(window).scroll(function() {
var hT = $('#google-map').offset().top,
hH = $('#google-map').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
if (!google) {
google = true; // stop the check
// enter your loading script here, use debounce and promise for async.
}
}
});
根據musefan的建議修改你也可以讓它像
var $googleMap = $('#google-map'); // use a ref
var $window = $(window); // use a ref
var google = false;
$(window).scroll(function() {
var hT = $googleMap.offset().top,
hH = $googleMap.outerHeight(),
wH = $window.height(),
wS = $window.scrollTop();
if (wS > (hT+hH-wH)){
// if you do the unregister approach, you dont even need to check for google var
if (!google) {
google = true; // stop the check
// enter your loading script here, use debounce and promise for async.
// unregister your event as musefan said
}
}
});
這有效,只觸發一次。 謝謝 Sprep && Musefan
var fired = false;
$(window).scroll(function() {
var hT = $('#google-map').offset().top,
hH = $('#google-map').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
wB = hT+hH-wH;
if (wS > wB && fired === false ){
console.log('This will happen only once');
fired = true;
$.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
initialize();
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.