views:

7731

answers:

10

Any idea why the piece of code below is not working?

var code = "<script></script>";
$("#someElement").append(code);
+13  A: 

I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );

From: http://mg.to/2006/01/25/json-for-jquery

acrosman
The <script> tag needs to be added to the DOM itself, not to the innerHTML of an existing element.
Diodeus
Thanks @acrostman, it actually works this way.
Dan
@Diodeus the innerHTML is part of the DOM and it's parsed on the fly by the browser, so this is a valid case.
Christian Toma
Jacco
I believe it does, although to be honest I haven't tested in carefully in several months.
acrosman
+4  A: 

What do you mean "not working"?

jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -

$('#someElement').append('<script>alert("WORKING");</script>');


Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.

J-P
A: 

Is there any way to turn off that behavior? It's annoying when trying to detect when the script has been fully loaded on a slow network.

A: 

Is there a way to append " " html without the code being run?

Juan
A: 

I want to do the same thing but to append a script tag in other frame!

var url = 'library.js'; 
var script = window.parent.frames[1].document.createElement('script' ); 
script.type = 'text/javascript'; 
script.src = url;
$('head',window.parent.frames[1].document).append(script);
Julio Montoya
A: 
<script>
    ...
    ...jQuery("<script></script>")...
    ...
</script>

The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.

Roman Odaisky
Or don't embed your javascript directly within the HTML document. External script files don't have this problem.
Ian Clelland
Escape sequences: `"\x3cscript\x3e\x3c/script\x3e"`. In XHTML, you only need to put in a commented-out CDATA block.
Eli Grey
+4  A: 

It is possible to dynamically load a JavaScript file using the jQuery function getScript

http://api.jquery.com/jQuery.getScript/

$.getScript('http://www.whatever.com/shareprice/shareprice.js', function() { Display.sharePrice(); });

Now the external script will be called, and if it cannot be loaded it will gracefully degrade.

Cueball
A: 

Here's how google analytics would do it:

$("#someElement").append(unescape('%3script src=blah.js%3E%3C/script%3E"));

systemride
A: 

This works.

var code = "<script>alert('Hi!');</scr"+"ipt>";
$('body').append($(code)[0]);

I am not really sure why, but it seams like ither jquery is doing something clever with scripts or some browsers dont like to have scripts added like html/text.

O and this also the way to add scripts to an iframe.

var code = "<script>alert('Hi!');</scr"+"ipt>";
$('iframe').contents().find('head').append($(code)[0]);

Darwin
+2  A: 

The Good News is:

It's 100% working.

Just add something inside the script tag such as alert('voila!');. The right question you might want to ask perhaps, "Why didn't I see it in the DOM?".

Karl Swedberg has made a nice explanation to visitor's comment in jQuery API site. I don't want to repeat all his words, you can read directly there here (I found it hard to navigate through the comments there).

All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an "evalScript routine" rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.

I believe that one of the reasons jQuery does this is to avoid "Permission Denied" errors that can occur in Internet Explorer when inserting scripts under certain circumstances. It also avoids repeatedly inserting/evaluating the same script (which could potentially cause problems) if it is within a containing element that you are inserting and then moving around the DOM.

The next thing is, I'll summarize what's the bad news by using .append() function to add a script.


And The Bad News is..

You can't debug your code.

I'm not joking, even if you add debugger; keyword between the line you want to set as breakpoint, you'll be end up getting only the call stack of the object without seeing the breakpoint on the source code, (not to mention that this keyword only works in webkit browser, all other major browsers seems to omit this keyword).

If you fully understand what your code does, than this will be a minor drawback. But if you don't, you will end up adding a debugger; keyword all over the place just to find out what's wrong with your (or my) code. Anyway, there's an alternative, don't forget that javascript can natively manipulate HTML DOM.


Workaround.

Use javascript (not jQuery) to manipulate HTML DOM

If you don't want to lose debugging capability, than you can use javascript native HTML DOM manipulation. Consider this example:

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "path/to/your/javascript.js";    // use this for linked script
script.text  = "alert('voila!');"               // use this for inline script
document.body.appendChild(script);

There it is, just like the old days isn't it. And don't forget to clean things up whether in the DOM or in the memory for all object that's referenced and not needed anymore to prevent memory leaks. You can consider this code to clean things up:

document.body.removechild(document.body.lastChild);
delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load.

The drawback from this workaround is that you may accidentally add a duplicate script, and that's bad. From here you can slightly mimic .append() function by adding an object verification before adding, and removing the script from the DOM right after it was added. Consider this example:

function AddScript(url, object){
    if (object != null){
        // add script
        var script   = document.createElement("script");
        script.type  = "text/javascript";
        script.src   = "path/to/your/javascript.js";
        document.body.appendChild(script);

        // remove from the dom
        document.body.removeChild(document.body.lastChild);
        return true;
    } else {
        return false;
    };
};

function DeleteObject(UnusedReferencedObjects) {
    delete UnusedReferencedObjects;
}

This way, you can add script with debugging capability while safe from script duplicity. This is just a prototype, you can expand for whatever you want it to be. I have been using this approach and quite satisfied with this. Sure enough I will never use jquery .append() to add a script.

Happy Coding,
Hendra Uzia.

Hendra Uzia
Great explanation, thanks! But was is "UnusedReferencedObjects"?
acme
Thanks. I presume you were referring to the first occurrence of "UnusedReferencedObjects", that supposed to be any object you created in the script you load. I guess you better understand if you see what DeleteObject function does, it simply delete any object you passed to the function. I'll add some comment in the code to be clear. :)
Hendra Uzia