单页应用——基于局部视图动态加载js文件 [英] Single page application - load js file dynamically based on partial view

查看:36
本文介绍了单页应用——基于局部视图动态加载js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 Angular 并按照这里的教程 - http://docs.angularjs.org/tutorial/step_00

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

我从 GitHub 下载了种子示例,效果很好.不过我有一个问题 - 如果局部视图需要引用外部 js 文件,是否需要在开始时将其添加到 index.html 文件中?我希望应用程序尽可能精简,并且只想包含当前视图所需的 js 引用.是否可以根据视图动态加载js文件?

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?

推荐答案

这对我有用.我想我会把它发布给任何寻求最轻量级解决方案的人.

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

我在页面的 html 标签上有一个顶级控制器,每个局部视图都有一个辅助控制器.

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.

希望能节省一些时间.

这篇关于单页应用——基于局部视图动态加载js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆