How to stop widgets.js parsing entire document when script finishes loading?


#1

Hi,

I would like to know if there is a way to prevent twitters widget.js from parsing the entire document on page load. The reason is because I only want to load the widgets at certain points on the page when they are required.

    <script id="twitter" charset="utf-8">
    !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>

At the moment it automatically loads all widgets on the page when i include this script. How can I prevent this?

Thanks


#2

Twitter’s widgets.js scans the entire document to search for elements and class names matching a widget.

You could remove the expected CSS class for the initial load, swap back, and execute twittr.widgets.load() on a parent fragment when it enters the viewport.
https://dev.twitter.com/web/javascript/initialization

You could also use a progressive loader of choice and call a JavaScript factory function when you would like to display the widget on the page.
https://dev.twitter.com/web/javascript/creating-widgets


#3