-1

I'm creating a widget that displays several third party widgets that you can toggle through, however, I don't want the widget to load all the widgets on page load to save requests. I only want to load the other widgets once the user selects one from the menu.

Is there any way to load in these scripts on the fly, without resorting to housing the content in iframes?

an example would be the twitter widget:

<a  height="336" class="twitter-timeline" data-dnt="true" href="https://twitter.com/" data-widget-id="mytwitteraccount">Tweets by @</a>

<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

Best solution?

flyagaricus
  • 119
  • 2
  • 8
  • Couldn't you just call the JS within the script tag in your example when you want to load the script? You could also duplicate that approach for other scripts? – imcg Feb 18 '14 at 20:32

1 Answers1

0

Have you consider using Jquery getScript. What does is to load a JavaScript file from the server and the script is executed in the global context.

http://api.jquery.com/jquery.getscript/

From Jquery samples:

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});

Recently a similar question was posted where requirejs was better suited for the task in case it also helps:

RequireJS Demo

Community
  • 1
  • 1
Dalorzo
  • 19,312
  • 7
  • 50
  • 97