Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS: Load CSS and JS files dynamically

I am in the middle of developing a web app. I am using AngularJS for loading all the files dynamically into the UI.

I have an index.html file into which all the files will be loaded dynamically on-click or on-load.

//index.html
<signin button> <signup button> // etc.,
//on-clicking signin button a SignIn-page will load in the below div

<div id="bodyview"></div>
// end of index.html

Now my sign-in page looks somewhat like the below structure

    /*a div where my accordion menu will load when the 
     *below submit button is clicked*/

    <div id="menu"></div>

    //other sign-in-form stuff will follow on...

    //submit button at the end
    <submit button> //only on clicking the submit button the menu will be loaded

Now my problem is, though I'm able to load the accordion menu.html file, I'm not able to load the css and js files it is dependent on. I have researched on stackoverflow but none worked for me.

Can anybody please help in determining a way for loading the css and js dependencies using AngularJS

like image 869
Roopa Avatar asked Jul 17 '13 08:07

Roopa


People also ask

How do you load CSS and JS files dynamically?

Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.

How do I load a CSS file after page load?

To load CSS Files asynchronously in both Chrome and Firefox, we can use “preload” browser hint and “media='print'” attribute along with onload event feature in a ordered way. you may use the codes below to load CSS Files without render-blocking resources features in Firefox and Chrome.


2 Answers

Just write a service to add CSS and JS files to the <head>

Here is a example service which is used to dynamically load CSS files.You can modify it easily to load JS files.

https://github.com/Yappli/angular-css-injector

like image 126
rppig Avatar answered Sep 28 '22 03:09

rppig


Currently I use angular-css: https://github.com/door3/angular-css Imho, it's one of the best and most flexible solutions at the moment.

like image 41
Olga Gnatenko Avatar answered Sep 28 '22 02:09

Olga Gnatenko