0

my problem is as follow. I have a multiple script blocks that contain javascript code type of text/plain. So my question is is there any script that i can dynamically convert them from text/plain to text/javascript type and execute its content ? The problem i'm having is the place of execution, because scripts contain document.write so the output is appended in the end of the html not on the location of the script itself.

eg: let's say something like this

<script type="text/plain">alert('hello world');</script>
<script type="text/javascript">
$(document).ready(function(){
    $("script[type*=plain]").each(function() {
        $(this).attr('type','text/javascript');
    });
});
</script>

thnx

swirm
  • 23
  • 1
  • 5
  • I created a JS function which is called after every text/plain script block. It's the simplest solution i came up with. Not the most elegant but still. – swirm Sep 02 '13 at 06:30

3 Answers3

0

Modifying a script element in place doesn't cause it to be executed. You need to create a new script element with the appropriate content. Another option is to eval() the contents of the old element:

$(document).ready(function(){
    $("script[type*=plain]").each(function() {
        eval($(this).text());
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • i did tried it with document.createElement and replaceChild but the problem is a place of execution. – swirm Aug 22 '13 at 06:57
  • can you add what you tried to your question, and make a fiddle demonsatrating it? – Barmar Aug 22 '13 at 06:59
0

You can go with some nasty approach, of selecting the tag with type=plain and then accessing its innerText attribute, assigning it to eval method.

var el = $("script[type*=plain]")[0];
eval(el.innerText);

But I'd try to avoid using eval

If there's a different approach I'm not aware of it, and for this I am sorry.

Community
  • 1
  • 1
Sgoldy
  • 786
  • 3
  • 14
0

You can not make document.write to place it's output in place of <script> element if you change script's type, because entire page's javascript code woudn't re-run every time you add new <script> or evaluating existing one.
If you want to replace <script type="text/plain"> with the result of script execution, you can return some string from that script instead of using document.write and then insert this string in place of <script type="text/plain"> element:

<script type="text/plain">
  var result = "line1<br>";
  result += "line2"; 
  alert('hello world');
  result
</script>
<script type="text/javascript">
$(document).ready(function(){
  $("script[type*=plain]").each(function() {
    $(this).replaceWith(eval($(this).text()));
  });
});
</script>
ataman
  • 2,644
  • 17
  • 22