I’ve observed that when I utilize jQuery’s .html('...')
method to insert markup containing an external <script src="..."></script>
tag, jQuery doesn’t insert the script tag directly into the DOM as is. Instead, it retrieves the contents of the script first and then generates a new inline <script>
tag containing the original contents.
In other words, if the inserted HTML contains:
<script src="xyz.js"></script>
jQuery transforms it into:
<script> ... contents of xyz.js ... </script>
However, because my content security policy (CSP) prohibits inline script tags, the browser now refuses to execute this script. I understand that jQuery has to parse the script tags since setting HTML via .innerHTML won’t execute scripts contained in the markup. But why is an external script transformed into an inline script? Is there a way to configure jQuery’s behaviour here or do I have to override .html()
myself?
2
Answers
Had the same trouble some days ago
Here’s what i did;
Variable data is containing the html as plain string..
Variable container is my body where i want to append (jQuery El)
Something like this ought to work. We can just
.appendTo()
it, instead of using.html()
.https://codepen.io/Terrafire123/pen/mdaKpJG?editors=1010