我成功地动态编写了脚本标签,但是,当脚本标签最终附加到head标签之后,它不会执行。如果我将标签静态放置在头部,则动态创建的脚本标签会起作用。
有什么想法为什么在脚本标记加载后不执行?
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
console.log('working')
console.log("Coordinates: ", position.coords);
const { latitude, longitude } = position.coords;
// Use jquery to dynamically create a script tag and add lat and long to the src attribute
var tag = $('<script>');
tag.defer = true;
tag.onload = function () {
console.log('The script is loaded');
}
tag.attr('src', `https://darksky.net/widget/default/${latitude},${longitude}/us12/en.js?width=100%&height=350&title=FullForecast&textColor=333333&bgColor=FFFFFF&transparency=false&skyColor=undefined&fontFamily=Default&customFont=&units=us&htColor=333333<Color=333333&displaySum=yes&displayHeader=yes`);
tag.attr('type', 'text/javascript');
console.log('appending to head')
// append it to the body
$('body').append(tag);
})
} else {
// x.innerHTML = "Geolocation is not supported by this browser.";
}
});
应该加载脚本。