首页 > 解决方案 > 动态生成的脚本标签附加到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&ltColor=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.";
        }

    });

应该加载脚本。

标签: javascriptjqueryhtml

解决方案


推荐阅读