Home > Mobile >  Dynamic script tag not loading, can't see network traffic for it
Dynamic script tag not loading, can't see network traffic for it

Time:08-12

This code doesn't seem to load dynamically. Am I doing something wrong? Is there a better way.

<html>
<head>
</head>
<body>
    <script id="sovrn-ad" async defer crossorigin="anonymous" type="text/javascript" src=""></script>

    <script type="text/javascript">

        var scriptElement = document.getElementById('sovrn-ad');

        if (window.innerWidth < 480) {
            scriptElement.src = "https://ap.lijit.com/www/delivery/fpi.js?z=1056094&width=320&height=50";
        } else {
            scriptElement.src = "https://ap.lijit.com/www/delivery/fpi.js?z=1056094&width=320&height=50";
        }
    </script>
</body>
</html>

CodePudding user response:

If I'm understanding the problem correctly, you're trying to dynamically load a script based off the window's conditional width. In addition, based on the comment, it sounds like you need the updated script to load right after it has been placed in the document. To do this, try the following solution:

<script id="init-script" type="text/javascript">
    function insertAfter(referenceNode, newNode) {
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    }

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = 'async';
    script.defer = 'defer';
    script.crossOrigin = 'anonymous';
    if(window.width < 480) {
        script.src = "Script if less than 480px";
    } else {
        script.src = "Script if greater than 480px";
    }
    insertAfter(document.getElementById('init-script'), script);
</script>

What this does:

The above script is doing a few things.

  1. First, it defines a function called insertAfter() that will effectively insert your new element after this script tag but before any additional siblings.

  2. Second, it then defines the script tag using the attributes you defined above and also provides the conditional logic based on the window.width < 480 to load the appropriate script source value.

  3. Finally, it passes the current script id element found using document.getElementById and the newly created script element to your original function which will append it directly below the script tag. Depending on where you place the init-script it will either append directly below in the head or body element.

Credit:

insertAfter() function derived from this answer: How to insert an element after another element in JavaScript without using a library?

  • Related