How to embed <script> with Prototype?

I use the prototype insert function to add some html that contains <script>...</script> . And in this script, I define a new function. And since I read here Prototype runs a script that is inside the <script> tags and then removes it, but all functions should remain available. But from now on, I can’t start my new function.

  $('some_id').insert({ bottom: '<script> ... </script>' }); 

How to solve it? It would be best not to remove the <script> tags.

EDIT:

Now I have done it as follows:

 var add_here = document.getElementById('prepayment_group_items'); var src = document.createElement('div'); src.innerHTML = 'a lot of html with script tags'; add_here.appendChild(src); 
+4
source share
3 answers

This function will add a script tag to the page title with any content that you pass to it.

 function insertScript(script_text) { var script_tag = document.createElement('script'); script_tag.type = "text/javascript"; var script = document.createTextNode(script_text); script_tag.appendChild(script); document.getElementsByTagName('head')[0].appendChild(script_tag); } 

I am more familiar with jQuery than with a prototype, so I just did it in pure JS.

Translate the part in which I create the element and the part in which I get the HEAD element in Prototype if you want, but use the call to appendChild instead of the Prototype insert function, as it will just do what you ask and not evaluate JS.

Of course, now that I’m looking at what you are asking for, you can also just try changing the code you are inserting to something like:

 window.update_12345 = function() {...} 

I'm not sure if this will work or not, but it's worth a try.

+2
source

If you want to include JavaScript in your head, you can do something like this:

 $$('head').first().insert({ bottom: new Element('script', { type: 'text/javascript' }).update('function helloWorldToConsole(){console.log("Hello World!")}') }); 

Creates a new SCRIPT tag and inserts it at the bottom of your HEAD. But it would be much nicer to add an external JavaScript file as follows:

 $$('head').first().insert({ bottom: new Element('script', { type: 'text/javascript', src: 'http://www.example.com/path/file.js' }) }); 

You can use functions later in your scripts.

0
source

try it.

  $('<script></script>',{ type:'custom', id:'script1' }).appendTo('head').attr('type','text/javascript'); $('#script1').append(< add js code here >); 

});

-one
source

All Articles