I am successful with dynamically writing a script tag, however, when the script tag is finally appended to the head tag it does not execute. The dynamically created script tag works if I statically place the tag in the head.
Any thoughts on why this is not executing after the script tag has loaded?
$(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.";
}
});
The script should be loaded.