0

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&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.";
        }

    });

The script should be loaded.

  • https://api.jquery.com/jQuery.getScript/ – James Ashok Aug 09 '19 at 05:28
  • Script tag gets appended as desired, but results in `Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.`. Solution: don't use `document.write` (you should probably never be using `document.write` anyway) – CertainPerformance Aug 09 '19 at 05:28

0 Answers0