December 2, 2020 code

I have nothing against jQuery. It does exactly what it’s supposed to do. jQuery simplifies a lot of the complicated things in JavaScript, so it is easier to use (and we do use it here at Urban Influence).

But why use an 87KB file only to write more JavaScript that is only being used for AJAX to return some JSONP? Every project doesn’t need it. So let’s use fetch instead to hit the endpoints of the Instagram API.

See the Pen Instafetch.js Example by Thomas Vaeth (@thomasvaeth) on CodePen.

The Fetch API

The Fetch API provides a fetch() method defined on the window object, which can be used to perform requests. fetch() returns a Promise that can be used to retrieve the response of the request. It is an easier way to make web requests and handle responses than using a XMLHttpRequest.

fetch(url, options).then(function(response) {
  // handle HTTP response
}.catch(error) {
  // handle network error

However, the Fetch API only supports JSON, but what about JSONP? The Instagram API requires JSONP because it is a cross-domain request. Fetch-JSONP is being used as a dependency to allow JSONP data-types while using the Fetch API.

Now we’re good to go on most browsers except for Internet Explorer. It’s pretty common for something not to work on IE and having to find a workaround, so this is no different from other things we build. The Fetch API returns a Promise, but IE doesn’t know what a Promise is. You will see “Promise is undefined” in the console and the Instagram feed will be empty. We’re using the ES6-Promise Polyfill to support IE until fetch() is supported. So that’s where the plugin goes from 3KB to 10KB (but it’s still less than 87KB).


Instafetch.js is currently available on NPM, Bower, and GitHub.


npm install --save instafetch.js es6-promise


bower install instafetch.js
<script type="text/javascript" src="path/to/bower_components/instafetch.js/dist/instafetch.min.js"></script>


Download the script or the minified version in the dist folder.

<script type="text/javascript" src="path/to/instafetch.min.js"></script>

How to Use

The Instagram API uses the OAuth 2.0 protocol, so you’re going to need an access token. The easiest way to get your access token is login to Instagram on your browser and generate one on Pixel Union.

<div id="instafetch"></div>
<script type="text/javascript">
    accessToken: 'ACCESS TOKEN',
    target: 'instafetch',
    numOfPics: 20,
    caption: false

Instafetch.js will look for an element with the ID of instafetch by default. The target element can be changed when initializing the plugin.

The plugin also allows you to set the number of items to return from your feed and if you want to include the captions.

Demo & Documentation



Other posts