Skip to content

Instantly share code, notes, and snippets.

@endorama
Last active October 11, 2018 07:28
  • Star 36 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save endorama/7369006 to your computer and use it in GitHub Desktop.
AngularJS 1.2.0 lazy load script in partials
/*
* Angular LoadScript
*
* Let angular load and execute lazy javascript from partials!
*
* This module is the result of this issue: "1.2.0rc1 regression: script tags not loaded via ngInclude"
* Issue url: https://github.com/angular/angular.js/issues/3756
*
* As of Angular 1.2.0 the ngInclude scripts does not permit execution of javascript from included partials.
* This little module execute code inside script tags with "javascript-lazy" attribute after partial loading,
* thus re-enabling this feature.
*
* ( please have a look at the issue comments, this angular feature was never planned nor included properly,
* was only a drawback of using jQuery for partial inclusion )
*
* This angular module have been created by @endorama (https://github.com/endorama) based upon the code
* posted by @olostan (https://github.com/olostan)
*
* Simply add this file, load ngLoadScript module as application dependency and use type="text/javascript-lazy"
* as type for script you which to load lazily in partials.
*
* License: 2013 - released to the Public Domain.
*/
/*global angular */
(function (ng) {
'use strict';
var app = ng.module('ngLoadScript', []);
app.directive('script', function() {
return {
restrict: 'E',
scope: false,
link: function(scope, elem, attr) {
if (attr.type=='text/javascript-lazy') {
var code = elem.text();
var f = new Function(code);
f();
}
}
};
});
}(angular));
@prasanthkc
Copy link

thanks, awesome script, helped me.

@subudeepak
Copy link

Thanks awesome .. I have a small improvement ..
https://gist.github.com/subudeepak/9617483#file-angular-loadscript-js

Copy link

ghost commented Dec 17, 2014

👍

@kshyju
Copy link

kshyju commented May 7, 2015

Thanks ! You are a life saver 😄 😚

@rodrigogalindez
Copy link

Ciao Edoardo ! Grazie per la directive. However I can't seem to make it work. Trying to load Stripe Checkout, but it doesn't load the script. Any ideas? The directive is being loaded properly.

@rodrigogalindez
Copy link

Ciao Edoardo ! Grazie per la directive. However I can't seem to make it work. Trying to load Stripe Checkout, but it doesn't load the script. Here's the code in my app.js file:

angular
    .module('orderFormApp', [
        'ngAnimate',
        'ngCookies',
        'ngResource',
        'ngRoute',
        'ngSanitize',
        'ngTouch',
        'LocalStorageModule',
        'ngFileUpload'
    ])
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/step-1.html',
                controller: 'Step1Ctrl'
            })
            .when('/step-2', {
                templateUrl: 'views/step-2.html',
                controller: 'Step2Ctrl'
            })
            .when('/step-3', {
              templateUrl: 'views/step-3.html',
              controller: 'Step3Ctrl'
            })
            .when('/order-confirmation', {
              templateUrl: 'views/order-confirmation.html',
              controller: 'OrderConfirmationCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    });

And here is the code in /directives/javascript.lazy.js:

'use strict';

/**
 * @ngdoc directive
 * @name orderFormApp.directive:javascriptLazy
 * @description
 * # javascriptLazy
 */
angular.module('orderFormApp')
  .directive('script', function () {
    return {
          restrict: 'E',
          scope: false,
          link: function(scope, elem, attr) {
            if (attr.type=='text/javascript-lazy') {
                console.log('runs');
                var code = elem.text();
                var f = new Function(code);
                f();
            }
          }
        };
});

In the template, I'm having this:

<form action="/charge" method="POST">
            <script type="text/javascript-lazy"
            src="https://checkout.stripe.com/checkout.js" class="stripe-button"
            data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
            data-image="/img/documentation/checkout/marketplace.png"
            data-name="Stripe.com"
            data-description="2 widgets"
            data-amount="2000">
            </script>
        </form>

However, it won't work. I also replaced the code in the directive with a console.log('runs'); to see if the directive was being loaded in the view, and it works. Any ideas? Thanks!

@Acksop
Copy link

Acksop commented Jul 30, 2015

I have found a bug with this addition on angular.js when a tried to lazy load a old WYSIWYG Editor...
Maybe this can be useful.

http://collaboration.infoartsmedia.fr/files/standard/4/CV/applicationangularbugonlazyloadtar_45805.gz
Thanks for this.

@isherwood
Copy link

JSHint throws an eval warning: The Function constructor is a form of eval. Is there another way to accomplish the same?

@gouravsood
Copy link

Thanks a lot @endorama for sharing this module. This helped me to solve the webflow.js load issue with angularjs (http://forum.webflow.com/t/use-of-web-app-frameworks-like-angular/3191/10).

Thanks,
Gourav

@m24927605
Copy link

Sorry,please tell me how can I load webflow.js with Angular4?Is there any solution?

@DoanVanThuong
Copy link

@m24927605 getting error like same you, have you resolve it??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment