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>
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:
What this does:
The above script is doing a few things.
First, it defines a function called
insertAfter()that will effectively insert your new element after this script tag but before any additional siblings.Second, it then defines the script tag using the attributes you defined above and also provides the conditional logic based on the
window.width < 480to load the appropriate script source value.Finally, it passes the current script
idelement found usingdocument.getElementByIdand the newly created script element to your original function which will append it directly below the script tag. Depending on where you place theinit-scriptit will either append directly below in theheadorbodyelement.Credit:
insertAfter()function derived from this answer: How to insert an element after another element in JavaScript without using a library?