views:

124

answers:

2

I am using the JSONP/dynamic-script-tag technique to perform cross-domain AJAX (There's no XML, but you know what I mean).

Initially, I wrote my own solution, but I could not come up with an elegant way to remove the script after it executed. My strategy was just to pass an ID and on the callback remove the associated script, but I realized this would prevent caching, which I do not want to do.

That went something like:

1) Dynamically insert: <script src="http://example.com/handler.php?callback=x&amp;scriptid=y"&gt;&lt;/script&gt;.

2) The script loads and runs x(); removeScript(y); where removeScript took the appropriate script element out of the head element.

It worked great but ruined caching. So I was excited to learn jQuery provides a jsonp method and quickly implemented it, figuring they had got this all figured out. Instead jQuery leaves the script element there.

Is there a clean way to remove these elements?

A: 

Why would you want to remove them? Only web geeks look at the source code of a page, and chances are you won't get paid by web geeks to make a website. They're harmless, so you don't need to go all the trouble to remove the tags.

zneak
-1 because the point isn't really about "web geeks" - it's about the memory requirements to load the DOM tree. Eventually the number of script tags that Fletcher created will overflow the memory that the browser is using to store the DOM and your scripts will probably stop executing (such is the case in Chrome). You are efectively leaking memory.
ivans
@ivans How many `<script>` elements does it take for Chrome to stop executing Javascript?
zneak
In my experience it's more related to the size of the returned content than the number of requests itself. For instance, I made a JSONP driven chat site (www.brukator.com) and after about 8-10 thousand requests are received, Chrome stops script execution. I can perform more detailed analytics if you want a closer-to-exact number?
ivans
@ivans No thanks; but maybe you could still do it and send it to the Chrome team. I'd call that a bug.
zneak
I'm not 100% certain it's a bug: this situation causes a bar to appear at the top of the window and it clearly says something like "scripts disabled due to large memory consumption."
ivans
+1  A: 

Thanks to your question I discovered this project on code.google: jquery-jsonp . this plugin provides some functionality that jquery does not.

I never used it but seems to be cool and handle a great variety of things, including caching. You can find some examples of its usage here: http://code.google.com/p/jquery-jsonp/wiki/TipsAndTricks

Matias