I'm using XSLT to transform an XML into HTML on the client side (Chrome browser).
I'm trying to add <script>
HTML tag to the XSLT but it seems that the code in it is never evaluated on the generated HTML, although I've specified defer
.
On the other hand, onclick
event itself runs OK.
Here is an example of the XSLT which demonstrates the issue:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"
encoding="UTF-8"
indent="no"/>
<xsl:template match="/">
<html>
<head>
<script type="text/javascript" defer="defer">
<xsl:text>
<![CDATA[
function test(){
window.alert('Test');
}
]]>
</xsl:text>
</script>
</head>
<body>
<button onclick="window.alert('Test')">This works</button>
<br/>
<button onclick="test()">This does not work</button>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The XML file does not matter is this example. You can try the above example on W3Schools online XSLT transformation
In this example, clicking on This does not work
yields an error: Uncaught ReferenceError: test is not defined
.
What am I doing wrong here?
Update
The problem only happens when I'm performing the XSLT transformation itself in javascript. Here is the piece of code that is doing that in my case:
var processor = new XSLTProcessor(),
htmlResult;
processor.importStylesheet(xsl);
htmlResult = processor.transformToFragment(xhr.responseXML, document);
document.getElementById("result").appendChild(htmlResult);
Update
I also need the following to work correctly when they appear in the XSLT file:
- Loading external javascript files using
script
element:
<script type="text/javascript" src="/somelibrary.js" />
- Bare
<script>
elements with javascript code in them, that call functions which are declared in an external javascript file, loaded by an earlierscript
element.