Search code examples
javascripthtmlspringthymeleaftemplate-engine

How to add Script tag by inLine Script in Thymeleaf?


I have written following code into Thymeleaf template to load jQuery from server if cdn link fail.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/vendor/jquery-3.2.1.min.js"><\/script>');
</script>

Thymeleaf is interpreting document.write('<script src="js/vendor/jquery-3.2.1.min.js"></script>') as script tag which should imterpret as a string.

I'm getting following error near <\/script> tag.

org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.

Any solution or work around for this problem?

Thanks :)


Solution

  • You can wrap your scripts in CDATA blocks for this:

    <script>
        // <![CDATA[
        window.jQuery || document.write('<script src="js/vendor/jquery-3.2.1.min.js"><\/script>');
        // ]]>
    </script>