Skip to content

Commit

Permalink
Preconnecting for amp-img (#10142)
Browse files Browse the repository at this point in the history
  • Loading branch information
wassgha authored and cramforce committed Jun 30, 2017
1 parent 10b051a commit d44039a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
22 changes: 22 additions & 0 deletions builtins/amp-img.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,28 @@ export class AmpImg extends BaseElement {
}
}

/** @override */
preconnectCallback(onLayout) {
// NOTE(@wassgha): since parseSrcset is computationally expensive and can
// not be inside the `buildCallback`, we went with preconnecting to the
// `src` url if it exists or the first srcset url.
const src = this.element.getAttribute('src');
if (src) {
this.preconnect.url(src, onLayout);
} else {
const srcset = this.element.getAttribute('srcset');
if (!srcset) {
return;
}
// We try to find the first url in the srcset
const srcseturls = srcset.match(/https?:\/\/[^\s]+/);
// Connect to the first url if it exists
if (srcseturls) {
this.preconnect.url(srcseturls[0], onLayout);
}
}
}

/** @override */
buildCallback() {
this.isPrerenderAllowed_ = !this.element.hasAttribute('noprerender');
Expand Down
1 change: 0 additions & 1 deletion src/srcset.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {dev, user} from './log';
*/
let SrcsetSourceDef;


/**
* Extracts `srcset` and fallbacks to `src` if not available.
* @param {!Element} element
Expand Down
32 changes: 32 additions & 0 deletions test/functional/test-amp-img.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@ describe('amp-img', () => {
});
});

it('should preconnect the src url', () => {
return getImg({
src: '/examples/img/sample.jpg',
width: 300,
height: 200,
}).then(ampImg => {
const impl = ampImg.implementation_;
sandbox.stub(impl.preconnect, 'url');
impl.preconnectCallback(true);
const preconnecturl = impl.preconnect.url;
expect(preconnecturl.called).to.be.true;
expect(preconnecturl).to.have.been.calledWith('/examples/img/sample.jpg');
});
});

it('should load an img with srcset', () => {
return getImg({
srcset: 'bad.jpg 2000w, /examples/img/sample.jpg 1000w',
Expand All @@ -95,6 +110,23 @@ describe('amp-img', () => {
});
});

it('should preconnect to the the first srcset url if src is not set', () => {
return getImg({
srcset: 'http://google.com/bad.jpg 2000w, /examples/img/sample.jpg 1000w',
width: 300,
height: 200,
}).then(ampImg => {
const impl = ampImg.implementation_;
sandbox.stub(impl.preconnect, 'url');
impl.preconnectCallback(true);
expect(impl.preconnect.url.called).to.be.true;
expect(impl.preconnect.url).to.have.been.calledWith(
'http://google.com/bad.jpg'
);
});
});


describe('#fallback on initial load', () => {
let el;
let impl;
Expand Down

0 comments on commit d44039a

Please sign in to comment.