Loading a new script programatically in a Vanilla JS

Issue

This Content is from Stack Overflow. Question asked by Andrew Newby

I’m using Modernizr to check if the browser support intersectionobserver. If not, it should load a Polyfill we have that should do the trick. However, it seems that in Chrome < v50, it doesn’t do as expected:

Uncaught TypeError: document.body.append is not a function 

The code is:

if (Modernizr.intersectionobserver) {
    // supported already
} else {
   const script = document.createElement('script');
    script.id = 'pollyfill-intersection';
    script.src = 'https://www.example.com/2022/js/lib/polfill/IntersectionObserver.js';
    //script.async = true;
    document.body.append(script);
}

What am I doing wrong? Surely even a 2016 version of Chrome has document.body.append() ? Could the issue be a “race” one, where the DOM hasn’t loaded before my code runs?



Solution

Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?