24

In my AngularJS app, I've many controllers js files.

These controllers (one.ctrl.js,two.ctrl.js,...) needs to be included in my index.html file.

Directory Structure:

app/
   js/
      controllers/
         one.ctrl.js
         two.ctrl.js

Currently, above js files are included in index.html file as follows.

index.html:

<!--   other html components   -->

<script src="js/controllers/one.ctrl.js"/>
<script src="js/controllers/two.ctrl.js"/>
</body>
</html>

There are gonna be more *.ctrl.js files which are required to be included in index.html.

I need a way to automatically include all the *.ctrl.js files in controllers directory to index.html.

Findings:

From some SO questions,

Load JavaScript and CSS files in folders in AngularJS

How can I include all JavaScript files in a directory via JavaScript file?

I found that it cannot be done automatically and needs some server side scripting or build tools.

My Question:

Currently, I'm using yeoman which include grunt for build tool. So, my question is, How can those javascript files in a directory be automatically included in a html file?

2
  • I can give you an example with gulp.js. Will that do? Commented Jun 7, 2014 at 14:57
  • I haven't used gulp.js. I can try if it does the job. Commented Jun 7, 2014 at 15:13

3 Answers 3

13

You could use the grunt-include-source plugin

Using it you can define templates like these :

html: {
    js: '<script src="{filePath}"></script>',
    css: '<link rel="stylesheet" type="text/css" href="{filePath}" />',
  }

in your html file which will be expanded to include all your source js and css files present in your source location which can be configured in the grunt task

Sign up to request clarification or add additional context in comments.

1 Comment

Can you provide a full Gruntfile.js ?
7

Answering the general question of adding source files to index.html on demand and automatically and elaborating on the use of grunt-include-source.

This is for the following folder structure:

MyProject
|
+-- index.js
+-- Gruntfile.js
+-- package.json
+-- //other files
|
+--+ app
   +-- //app files (.html,.js,.css,.*)
  1. Install with npm i -D grunt-include-source grunt-contrib-watch.

  2. In your Gruntfile.js, add grunt.loadNpmTasks('grunt-include-source');

  3. Then you have to add a bunch of tasks to your Gruntfile.js, after which it should look like this:

    module.exports = function (grunt) {
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
            //...
            watch: {
                //...
                includeSource: {
                    // Watch for added and deleted scripts to update index.html
                    files: ['app/**/*.js','app/**/*.css'],
                    tasks: ['includeSource'],
                    options: {
                        event: ['added', 'deleted']
                    }
                }
            },
            includeSource: {
                options: {
                    //This is the directory inside which grunt-include-source will be looking for files
                    basePath: 'app'
                },
                app: {
                    files: {
                        //Overwriting index.html
                        'app/index.html': 'app/index.html'
                    }
                }
            }
        });
    
        //...
        grunt.loadNpmTasks('grunt-contrib-watch');
        grunt.loadNpmTasks('grunt-include-source');
    
        //...
        //Include sources, run the server, open the browser, and watch.
        grunt.registerTask('default', ['includeSource', 'watch']);
    };
    
  4. In your index.html, add this (the file path here looks inside the base path set in Gruntfile.js):

    <!-- include: "type": "css", "files": "**/*.css" -->
    <!-- /include -->
    <!-- include: "type": "js", "files": "**/*.js" -->
    <!-- /include -->
    
  5. Finally, on the command line:

    grunt
    

This should start off all tasks in sequence, and your index.html should be updated accordingly when a JS or CSS is added or removed.

This is how your index.html might look like with a small number of files:

<!-- include: "type": "css", "files": "**/*.css" -->
<link href="styles.css" rel="stylesheet" type="text/css">
<!-- /include -->
<!-- include: "type": "js", "files": "**/*.js" -->
<script src="_routes/routes.js"></script>
<script src="scripts/app.js"></script>
<!-- /include -->

Links:

Comments

1

You can use something like this:

(function loadScript() {
    var head = document.getElementsByTagName("head")[0];
    var done = false;

    var directory = 'libraries/';
    var extension = '.js';
    var files = ['functions', 'speak', 'commands', 'wsBrowser', 'main']; 

     for (var file of files){ 
        var path = directory + file + extension; 
        var script = document.createElement("script");
        script.src = path;

        script.onload = script.onreadystatechange = function() {
        // attach to both events for cross browser finish detection:
        if ( !done && (!this.readyState ||
           this.readyState == "loaded" || this.readyState == "complete") ) {
           done = true;
           // cleans up a little memory:
           script.onload = script.onreadystatechange = null;
           // to avoid douple loading
           head.removeChild(script);
        }
    };
  head.appendChild(script); 
  done = false;
 }
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.