views:

118

answers:

2

Hi!

I have a script element in my webpage, something like this:

<script id="myscript"></script>

Now, from a javascript file, I'm doing something like the following:

$('#myscript').src('http://foo.bar?callback=somefunc')

Now this remote script 'returns javascript' of the following form:

somefunc(somearg);

When I run all of this, things work neatly, the script gets loaded dynamically, and the 'somefunc' callback is executed.

The problem happens when I do the same thing again. Let's say I again call the same thing:

$('#myscript').src('http://foo.bar?callback=somefunc')

This, for some reason, DOESNT return the javascript call in Firefox only. (Works fine in IE - somefunc gets executed again as expected).

I can think of ugly workarounds (such as doing a $('head').append('<script...')) every time - but I'd like to know what's going on here.

Thanks in advance!

+1  A: 
Shog9
The reason I thought the latter solution is ugly is because it keeps appending script tags to the <head> of the page. Whereas, my intention is to keep only one such <script> tag.I also tried adding a getTime() do-nothing parameter, but that doesn't work as well. Maybe I'm doing something wrong...
Raj
You can delete them after they've loaded... But CMS's solution already does that, and it's built in to jQuery - so if that's what you're after, just go with it. :-)
Shog9
Yes :-). Thanks for your response!
Raj
+2  A: 

I would recommend you to use $.getScript instead of using a single script tag load scripts multiple times:

$.getScript("http://foo.bar?callback=somefunc");

That function will abstract the script element creation and its introduction to the DOM.

But it seems you are accessing a JSONP service, in that case you need only $.getJSON:

$.getJSON("http://foo.bar?callback=?", function(json){
  // callback
});
CMS
getJSON probably would'nt work since the remote URL doesn't return JSON. It returns a javascript code to call the callback function.However, I didn't try it since getScript works like a charm! Thank you so much! Adding to my yet-another-jquery-gem-that-i-didnt-know list :-)
Raj