I have a div on my page defined as follows:
<div id="scripts">
</div>
I want to dynamically change the contents of the div and load in some scripts using jQuery. I am doing it like this:
$('#scripts').html('<script language="JavaScript">pn = "landing page"; '+
'cms_1 = "content"; '+
'cms_2 = "promotional "; '+
'cms_3 = "campaign"; '+
'cms_s = "blk:us:dc"; '+
'cms_env = "dev"; '+
'cms_country = "USA"; '+
'<\/script>');
This is in the document.Ready function. However, when I view the source after the page is loaded, the div appears empty and I do not see the script tags. I thought that the script wasn’t getting added but when I add alert("done"); to the script. I get the alert which tells me that the code is executed.
Why can’t I see the changes made when I view the source? Is the Source html rendered before the document.ready function?
The
htmlfunction from jquery internally uses the innerHTML property of the browser when available. In general, script blocks inserted via innerHTML don’t get executed almost in any browser.Try creating a script tag with the content and appending it to the document instead, e.g.
After seeing your motivation in the comment, I have to add : although you can later physically remove a script tag from the site, this won’t have the effect of unloading its content (e.g. functions defined in the script). The only way to achieve that without refreshing the page is to encapsulate the objects defined in it and delete them manually. This is of course only possible if the content of the script was designed upfront in such a way.