Blog

AngularJS fix for duplicate iFrame requests with Internet Explorer

coding screen

AngularJS fix for duplicate iFrame requests with Internet Explorer

The ng-src AngularJS directive is used to bind an iframe source Url to a scope property. During performance testing, I noticed in IE (10 and 11), that the Url was being updated twice. This causes two GET requests, which slowed the page load down.

A GitHub issue logged in the AngularJS repository explained that I was not alone in this discovery and provided some workarounds including updating the AngularJS source (not a good idea!)

The code below is a directive (using TypeScript) for a custom iframe source which prevents the two requests. Note, I used AngularJS version 1.5.0 for testing.

 

export class IFrameSourceDirective implements ng.IDirective {
public link: ng.IDirectiveLinkFn;
public restrict: any;

constructor() { this.restrict = 'A'; this.link = ($scope: ng.IScope, $element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModelCtrl: ng.INgModelController): void => {
attrs.$observe('iframeSrc', (value) => {
if (value) {
attrs.$set('src', value);
}

});

}

/**

* @returns an instance of IFrameSourceDirective, instantiated with Angular parameters.

*/

public static Factory() {
var directive = () => {
return new IFrameSourceDirective();
};

return directive;

}

}

app.directive("iframeSrc", IFrameSourceDirective.Factory());

 

Usage:

< iframe iframe-src="{{myUrlPropery}}"></iframe>

 

This was a subtle issue, which could have had significant impact on usability. Hopefully this assists others working with AngularJS applications with the ng-src directive.

 

 

 

 

 

Share Article