jQuery - script tags in the HTML are parsed out by jQuery and not executed
As Pointy pointed out (excuse the pun), jQuery messes with the SCRIPT tags when you pass HTML to $()
. It doesn't remove them though -- it simply adds them to the DOM collection produced from your HTML. You can execute the scripts like so:
$.ajax({
url: 'example.html',
type: 'GET',
success: function(data) {
var dom = $(data);
$('#mydiv').html(dom.find('#something').html());
dom.filter('script').each(function(){
$.globalEval(this.text || this.textContent || this.innerHTML || '');
});
}
});
jquery html() strips out script tags
Edit: I'm tired and not thinking. You can just use the native innerHTML
method instead of .html()
:
$('#feedback-' + idfeedback)[0].innerHTML = x;
Original answer:
My hunch is that the answer you linked doesn't work for you because the included scripts are called with a src
attribute rather than script content between the <script>
and </script>
tags. This might work:
$.ajax({
url: 'example.html',
type: 'GET',
success: function(data) {
var dom = $(data);
dom.filter('script').each(function(){
if(this.src) {
var script = document.createElement('script'), i, attrName, attrValue, attrs = this.attributes;
for(i = 0; i < attrs.length; i++) {
attrName = attrs[i].name;
attrValue = attrs[i].value;
script[attrName] = attrValue;
}
document.body.appendChild(script);
} else {
$.globalEval(this.text || this.textContent || this.innerHTML || '');
}
});
$('#mydiv').html(dom.find('#something').html());
}
});
Note, this has not been tested for anything and may eat babies.
script tags in ajax response not being parsed by IE = 8
I found the problem.
My site uses html5 and thus relies on innershiv ( http://jdbartlett.com/innershiv/ ) for inserting elements into the dom for non-html5 browsers (for me this would be ie7/8)
I had forgotten that we have an automated script that calls innershiv on all jQuery insertion methods ( .html(), .append(), etc..)
The reason this was failing for me is that innershiv was circumventing jQuery's script evaluation.
The fix was to do the script evaluation from within the script that calls innershiv. JD Bartlett provides a more detailed explanation here: https://github.com/jdbartlett/innershiv/issues/4
When are JS scripts executed, if they are loaded with jQuery .html() function?
I have created two files:
js_test.html
:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div id="div1"></div>
<p id="clickable">Click!</p>
<script type="text/javascript">
$(document).ready(function(){
$("#clickable").click(function(){
$.ajax("js_test_insert.html").done(function(content){
$("#div1").html(content);
});
});
});
</script>
</body>
</html>
And js_test_insert.html
:
<script type="text/javascript">
alert("Before.");
$("#inserted p").css("background-color","yellow");
alert("Middle.");
$(document).ready(function(){
alert("Inserted ready!");
});
</script>
<div id="inserted">
<p>Hello, World!</p>
</div>
<script type="text/javascript">
alert("After.");
function test() {
alert("It should not run");
}
</script>
I've tried it on FF 18.0, Chrome 36.0 and IE 11.0 (also using emulation of previous IEs) and:
p#clickable
is clicked.- "Hello, World!" appears above "Click!".
- Alert "Before."
- "Hello, World!" becomes yellow.
- Alert "Middle."
- Alert "Inserted ready!" (
I don't understand why).ready()
is executed - Alert "After."
jQuery firstly inserts HTML, DOM is built, and then JS is executed (in order of appearance).
EDIT: Why .ready()
is executed? Because the event is still ,,in efect'' (the document is ,,ready'' all the time, isn't it?) -- so adding a new handler of this event causes an immediate execution of the handler.
Solved.
Script not executing with a dynamically generated JQuery script tag
When you insert a script tag manually like you are doing, that script is loaded asynchronously. That means that other parts of the page will NOT wait for that script to be loaded.
This is different than if the script tag is present in the source of the page because in that case, the script will load synchronously and other parts of the page will not execute until after that script is loaded.
The result of this is that the rest of your page javascript is executing BEFORE the dynamically inserted script tag has been loaded, parsed and run. Thus, you are trying to use jQuery before it's been installed.
I'm aware of two options for solving your issue:
Change the insertion of your jQuery script tag to something that loads synchronously. The only way I know of to do that is to use
document.write()
to write the new script tag to your document, not insert it into the head section like you're doing. Stuff that is added to the document withdocument.write()
is processed synchronously.Continue to insert your script dynamically like you are doing, but add a monitoring event so you will know when the script has been loaded successfully and only run your initialization code that uses jQuery AFTER you get that notification that jQuery has been successfully loaded.
There are also script loading libraries (such as require.js) that will do the second option for you.
jQuery: Parse/Manipulate HTML without executing scripts
FYI, Using unescaped in any JavaScript script causes this issue in a browser. Developers have to escape it anyway so there is no excuse. So you can "trust" that would break in any case.
<body>
<div>
<script>
alert('<script> tags </script> are not '+
'valid in regular old HTML without being escaped.');
</script>
</body>
See
http://jsbin.com/itevu
to see it break. :)
html() strips script tags in fancybox (jQuery) ajax call
I think you might need to add your script and html something separately. You can send the markup and script joined by a token over the wire. Split them up via javascript on the client. Then add the html into the fancybox element. The script may need to be added outside the fancybox element. Here is an example of how to add the html and script into the same element:
http://jsbin.com/otage3/2/edit
Hope this helps.
Bob
Related Topics
How to Set the Prototype of a JavaScript Object That Has Already Been Instantiated
Convert Time Interval Given in Seconds into More Human Readable Form
How to Intercept All Ajax Requests Made by Different Js Libraries
How to Redirect to an External Url from Angular2 Route Without Using Component
How to Replace Captured Groups Only
Executing JavaScript from Python
Prevent Jquery UI Dialog from Setting Focus to First Textbox
Why Does Isnan(" ") (String with Spaces) Equal False
Get Loop Counter/Index Using For…Of Syntax in JavaScript
Dynamically Arrange Some Elements Around a Circle
New Line in JavaScript Alert Box
Secure Random Numbers in JavaScript
Jqgrid - Maintain Check Box Selection State - Page Refresh/Redirect/Reload
Use $Http Inside Custom Provider in App Config, Angular.Js
JavaScript Number Split into Individual Digits