开发者

Repeated Javascript injections to make YouTube API calls?

I am creating a web page that utilizes the YouTube API. I want to be able to fire off an AJAX style call to the YouTube API every time the user takes certain actions and update in-page elements with the results of the calls. YouTube's documentation recommends using Javascript injection to get around the cross domain permission issues that would be involved with making AJAX calls to a foreign domain (gdata.youtube.com) from my web page. For example:

<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/users/GoogleDevelopers/uploads?alt=json-in-script&format=5&callback=showMyVideos">
</script>

This snippet placed inside the HTML BODY makes a video feed request from the "GoogleDevelopers" channel with the "callback" parameter causing a call to showMyVideos() when the call returns. showMyVideos(), not shown here and arbitrarily named, uses DOM calls to update a named DIV with the results of the call.

I want to do the same operation except dynamically instead of statically like shown above. For example, I have seen code like this:

var s = document.createElement('script');
    s.type = "text/javascript";
    s.src = "http://gdata.youtube.com/feeds/users/GoogleDevelopers/uploads?alt=json-in-script&format=5&callback=showMyVideos"
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(s);

My开发者_JS百科 concern is if I use this approach, since I will be making many AJAX calls, I will accumulate more and more dynamically generated Javascript DOM elements in the web page DOM tree, and I worry what consequences that might have to the browser or anything else.

Is there a way to do Javascript injection in this style without cluttering up the HEAD element lots of Javascript elements? A concise code sample would be appreciated.

-- roschler


Well, not that hard, after you've gotten your data you clean up by removing the script element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜