-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?

1
  • 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? Commented Feb 18, 2014 at 20:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

This could work. However, is there a way to pass this script some data before it's executed?
what is your back running on?
@flyagaricus I am sorry a typo... what is your back-end running on?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.