当我尝试将Google地图添加到WordPress主题时,我错过了一些东西。当我使用的插件Debug Bar WordPress的发展,它抛出一个JavaScript错误:为什么我的WordPress主题中出现Google Map JavaScript错误?
Script error.
line 0
我不能确定在问题下降而做研究,我想我的问题是,当我没有async defer
后开始调用地图的API时:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
看完之后:
Step 2: Add a map with a marker
我研究解决了我认为是这个问题,我跑过:
- How to add defer=“defer” tag in plugin javascripts?
- https://wordpress.stackexchange.com/questions/38319/how-to-add-defer-defer-tag-in-plugin-javascripts
- Script Loader tag
代码为的functions.php:
function call_the_js_files() {
if (is_page_template('page-foo.php')) :
wp_enqueue_script('google_api', 'https://maps.googleapis.com/maps/api/js?key=AP_KEY&callback=initMap', array('jquery'), '', true);
add_filter('script_loader_tag', function ($tag, $handle) {
if ('google_api' !== $handle)
return $tag;
return str_replace(' src', ' async defer src', $tag);
}, 10, 2);
wp_enqueue_script('google_map', get_template_directory() . '/js/google.js', array('jquery'), '', true);
endif;
add_action('wp_enqueue_scripts', 'call_the_js_files');
The co德为google.js:
(function($) {
$(function initMap() {
var uluru = {
lat: 11111111,
lng: 222222222
};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 15,
center: uluru
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var marker = new google.maps.Marker({
position: uluru,
map: map,
icon: iconBase + 'parking_lot_maps.png'
});
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
})(jQuery);
当我查看源我得到:
<script type='text/javascript' async defer src='https://maps.googleapis.com/maps/api/js?key=API_KEY;callback=initMap'></script>
<script type='text/javascript' src='site/location/for/js/google.js'></script>
,但我仍然抛出与调试工具栏的错误。有什么我失踪或做错了吗?我没有渲染地图的问题,我遇到的唯一问题是JavaScript错误。在开发中,我在Google上的当前API设置在限制条件下设置为None
。
当我在google map script error line 0
下进一步研究时,我碰到了Google Maps Script error in Onion.js,但我已经在我的header.php中运行了<meta http-equiv="X-UA-Compatible" content="IE=edge">
。
我觉得这里的问题是你的第二个脚本谷歌API加载到页面之前运行。如果您添加异步,其他资源将继续同时加载。此外,这将是一个愚蠢的问题,但你是在头部之间添加你的脚本,你有一个谷歌地图id的元素? –
它加载在页脚,是即时通讯元素。如上所述,它渲染罚款,但它会引发错误 –