views:

487

answers:

2

I'm using Prototype insert function to appent some html which contains <script>...</script>. And within this script I'm defining a new function. And as I read here Prototype runs script that is inside <script> tags and then removes it, but all functions should remain accessible. But from that moment I can't run my new function.

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

How to solve it? The best would be that it won't remove <script> tags.

EDIT:

By now I did it like this:

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);
A: 

This function will add a script tag to the head of the page, with whatever content you pass 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'm more familiar with jQuery than Prototype, so I just did this in pure JS.

Translate the part where I create the element and the part where I get the HEAD element into Prototype if you want, but use the call to appendChild instead of Prototype's insert function, since it will just do what you ask, rather than eval-ing the JS.

Of course, now that I look at what you're asking for, you might also just try changing the code you're inserting to something like:

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

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

pib
Thanks, I already did it using appendChild, but I was putting a little more then just `<script>`. I appended my solution to question
klew
A: 

If you want to include JavaScript into the head, you might do something like this:

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

This creates a new SCRIPT tag and inserts it to the bottom of your HEAD. But it would be much nicer if you add an external JavaScript file like this:

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

You can than use the functions later in your scripts.

Kau-Boy