J-bob
J-bob

Reputation: 9106

loading a bunch of angular directives and other js files on the front end

Is there a best practice with angular to have a common list of external javascript files and import that list into different templates HTML files? The idea being that I can have a global list of scripts that I just import into any template.

So basically what I want is a single html file with all the js scripts in common. The file may include directives that angular depends on i.e.

<script src="my_script.html">
<script src="another_script.html">
<script src="angular_directive.html">
...

And then I want to import these into angular_template.html and another_angular_template.html. Is there a good way to do this on the frontend? The main issue I've found is that I want to include Angular directives in this global file, but if you do that then angular can't initialize in the first place because there may directives in that file that the app depends on. Therefore, something like ng-include doesn't cut it.

I'm willing to use plain old javascript or jquery if that's necessary. How would I accomplish this?

Upvotes: 1

Views: 310

Answers (1)

Michael Hays
Michael Hays

Reputation: 6908

If it's scripts you want, try RequireJS - http://requirejs.org/docs/start.html

Not only will it handle all of this for you behind a single include, but it will also load only what you need, and it will load scripts in parallel. There are several solutions out there like this, but I recommend diving into this one to see how this is so beautifully solved.

You will end up with only a single script in your html file -- something like this:

<script data-main="scripts/main" src="scripts/require.js"></script>

And then you'll have one script (main.js in this example) that will hold the config of what scripts you want to make available, and any codependencies you want to preserve. Your scripts will take on a feel like this:

define(['angular.js','myscript.js'], function() {
   ...your dependent script goes here...
});

Additionally, it has a nice config system so you can manually set up dependencies in a single place. Then you can pretty much dispense with the module verbage I wrote above. But modules have been here for a while, it's a good thing to have.

Alternatively, $script does exactly the same thing. Not as full featured, but it's tiny -- http://www.dustindiaz.com/scriptjs

Upvotes: 2

Related Questions