javascript - 动态生成的脚本标签附加到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.";
}
});
应该加载脚本。
解决方案
推荐阅读
- node.js - 护照 saml 请求中缺少“目的地”属性
- php - 从 For 循环创建多个 SQL 数据
- html-framework-7 - 将数据动态添加到 Framework7 智能选择?
- vim - 终端模式下的 Vim 自动完成
- python - '☃'.encode("utf-8") 不同于 ord('☃')
- sql-server - 如何使用 symfony odm 连接 MSSQL
- floating-point - 64位十六进制转换为十进制
- spring - Flyway 还原迁移验证
- php - Spatie-laravel-analytics 包 ga:users 不准确
- python - Python:为简单的 OLS 循环变量