开发者

dynamically load external JS and write response to a div

I'm embedding a delicious feed into my page. When I just add the script tags inside the div it obviously loads before the rest of my JS (at the bottom of the page). I'd like to load this script into the specified div dynamically after all other js has loaded.

I've tried the getscript function, but it definitely breaks the page when I use it with .html():

$('#delicious').html(function(){
$.getScript("http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd"); 
});

I can't seem to wrap my head around how I can print the results 开发者_JAVA技巧of that file into the #delicious div.


If you want to display the script in the div, shouldn't it be something like this, making use of the callback function?

$.getScript("http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd", 
             function(data){
                $('#delicious').html(data);
            }); 

The result of $.getScript() is the XMLHTTPRequest object and it seems like you want the response text instead.

Also, it looks like the response from the URL you've given attempts to write the script into the document, thus overwriting all your page content. It that is your problem you might consider using an iframe and setting this URL as it's source.

I also seem to get different behaviour depending on whether the script is being loaded cross-domain or from the same domain - I'm not quite sure what to make of that since getScript() is supposed to work cross-domain.


It sounds like you want to use something like the window load event. Try adding a handler that looks like this:

$(window).load(function() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = "http://feeds.delicious.com/v2/js/bayonnebridge?title=My%20Delicious%20Bookmarks&icon=m&count=5&sort=date&tags&extended&name&showadd";
  $('#delicious').append(script);
});

Check out the jQuery .load() API for more information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜