[英]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.