Best approach to changing background image in AngularJs at runtime

I want to create a universal function that allows me to change the background image of any section. After going through the options, I found these two approaches. Want to choose the best approach for changing the image, because on one page I want to change the background many times. It will be available for four to five sections.

An approach

  • Using the directive checks for stack overflow.

  • There is also another approach to angular scope variables that we can update at run time.

    <div ng-style="{'background-image': 'url(/images/' + backgroundImageUrl + ')'}"></div> 

Required Use (with respect to the Directive)

 <body> <section backgroundImage url="{{backgroundImageUrl1}}"> ... </section> <section backgroundImage url="{{backgroundImageUrl2}}"> ... </section> <section backgroundImage url="{{backgroundImageUrl3}}"> ... </section> <section backgroundImage url="{{backgroundImageUrl4}}"> ... </section> </body> 

As shown above, I am going to update the background-image attribute for each section. If this property is set inside the CSS file, this will reduce the loading time of images. If we add inline CSS to HTML, all images will be uploaded to the DOM download. He will make an additional request to the server to get the images and upload them to the DOM. I would like to follow a strategy that will reduce load times in my SPA (single page application).

+4
source share
1 answer

I think the transition from <div ng-style="{'background-image': 'url(/images/' + backgroundImageUrl + ')'}"></div> should be more efficient.

You do not introduce yet another level of complexity, directives create areas that are viewed and digested, and directives must be compiled at the beginning.

Using symple ng-style along with some specific URL from the shoudl controller properties, only requests this active active image. Because of this, I believe that this should be the best solution.

0
source

All Articles