Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've just started learning Angular and following the tutorial here - http://docs.angularjs.org/tutorial/step_00

I'm downloaded the seed example from GitHub and it works great. I have a question though - if a partial view requires an external js file to be referenced, does it need to be added to the index.html file at the beginning? I want the app to be as lean as possible and only want to include the js references that are required for the present view. Is it possible to load the js files dynamically based on a view?

question from:https://stackoverflow.com/questions/15939913/single-page-application-load-js-file-dynamically-based-on-partial-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
574 views
Welcome To Ask or Share your Answers For Others

1 Answer

This just worked for me. Figured I would post it for anybody else seeking the lightest-weight solution.

I have a top-level controller on the page's html tag, and a secondary controller for each partial view.

In the top-level controller I defined the following function…

$scope.loadScript = function(url, type, charset) {
    if (type===undefined) type = 'text/javascript';
    if (url) {
        var script = document.querySelector("script[src*='"+url+"']");
        if (!script) {
            var heads = document.getElementsByTagName("head");
            if (heads && heads.length) {
                var head = heads[0];
                if (head) {
                    script = document.createElement('script');
                    script.setAttribute('src', url);
                    script.setAttribute('type', type);
                    if (charset) script.setAttribute('charset', charset);
                    head.appendChild(script);
                }
            }
        }
        return script;
    }
};

So in the secondary controllers I can load the needed scripts with a call like the following…

$scope.$parent.loadScript('lib/ace/ace.js', 'text/javascript', 'utf-8');

There's a slight delay before the objects contained in the external script are available, so you'll need to verify their existence before attempting to use them.

Hope that saves somebody some time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...