How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page.

Our team requires the count and names of all CSS files utilized on the webpage.

While I am still learning Angular, I have been informed that this task can be accomplished through directives, although I am unsure of the specific steps to take.

Your assistance would be greatly appreciated. Thank you in advance!

Answer №1

Have you already implemented Angular in your application? If so, the following jQuery code can help handle this task smoothly:

var stylesheets = []
$('head link[type="text/css"]').each(function(){
    stylesheets.push($(this).attr("href"));
});
console.log("List of CSS files:" + stylesheets.join());
console.log("Total number of CSS files:" + stylesheets.length);

Answer №2

Utilizing angular framework:

  .directive('cssCounter', ['$document', function($document) {

    function filterCSSLinks(link) {
      return link.type === 'text/css' || link.rel === 'stylesheet';
    }

    function updateScopeWithCssNames(scope, document) {

      var links = document[0].querySelectorAll('link');
      var linksArray = Array.prototype.slice.call(links, 0);
      var cssLinks = linksArray.filter(filterCSSLinks);
      var cssNames = cssLinks.map(function(cssLink) {
        return cssLink.href;
      });


      scope.cssFiles = cssNames;
    }

    return {
      link: updateScopeWithCssNames,
      template: '<p>Number of CSS files: {{cssFiles.length}}<ul><li ng-repeat="c in cssFiles">{{c}}</li></ul></p>'
    };
  }]);

An illustrative plunker can be accessed via the following link: http://plnkr.co/edit/TqNAOKw4biyA7akdHfa4

Answer №3

If you want to achieve this without relying on any external libraries, here is the way to go:

let allLinks = document.querySelectorAll('link');
let linksArray = Array.prototype.slice.call(allLinks, 0);
let cssStylesheets = linksArray.filter(function(link){return link.type === 'text/css';});
let cssFileNames = cssStylesheets.map(function(stylesheet){return stylesheet.href;});
let totalNumberOfCSSFiles = cssFileNames.length;
console.log("Total number of CSS files and their names:", totalNumberOfCSSFiles, cssFileNames);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scroll the div back to the top when the form is submitted

I have set up a form in a pop-up using Bootstrap modal. The form is quite long, so after submission, the message appears at the top of the form. However, I want it to scroll to the top when the user submits the form so they can easily see the message. Is ...

Interactive sidebar search component for Angular

Within my angular application, I have implemented a universal sidebar navigation directive that offers a variety of features, including a comprehensive search function for users (with multiple criteria, not just a simple text input). When a user performs ...

Troubleshooting Problems Arising from PHP, Ajax, and SQL Integration

I've been encountering an issue that seems simple, but I haven't been able to find a solution specific to my problem in the forums. The problem arises when I try to display a table of hyperlinks, each linked to an AJAX method with an 'oncli ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

Employing VUE.js for content retrieval

Is there an issue rendering 2 messages in vue.js on the front end? <template v-for="item in items"> <span>{{ afterpayMessage }}: {{ item.price }} with AfterPay</span> </template> <script> var afterpay = new Vue({ e ...

Discovering the function invoker when in strict mode

I am facing a challenge in my Angular controller where I have a function called getGames() that can be triggered by both the init() and update() functions. The issue is, I need to handle these two scenarios differently based on which function called getGam ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

What is the access URL when using Angular 2's npm start command?

When I execute npm start in my angular 2 project directory, the console response includes the following lines: Access URLs: ------------------------------------ Local: http://localhost:3000 External: http://10.28.93.96:3000 ------------------------- ...

Can implementing $routeProvider help reduce data usage on a network?

Take a look at this $routeProvider configuration for the navbar and let's assume there is no caching involved app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl : 'pages/home.html& ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

The function was expecting an array for ordering, but instead received an object

I need help filtering my results based on their position. Whenever I try to use the orderBy function, it breaks the page because the result is not an array. How can I fix this issue? I'm currently stuck at this point. This is how I attempt to filter ...

Facing issues with ReactCSSTransitionGroup as transitionAppear feature is not functioning

I'm having trouble with the appearance and disappearance of notifications. The transitionAppear property doesn't seem to be working as expected. I'm adding the notification popup item to the onBlur event. The animation for the leave event wo ...

I am having trouble scrolling through the main content when the side-drawer is open. How can I fix this issue?

When the sidebar is opened, I am facing issues with the main content scroll and certain fields such as select options and search bar not functioning properly. I have included the main content in the routes from which it is being loaded. However, the scroll ...

Guide to extracting the outcomes of a promise array and populating them into a new array using Protractor

I am facing a challenge with transferring data from an array of promises generated by the following code: element.all(by.repeater('unit in units')). It seems to be difficult for me to store this data into another array: element.all(by.repeater(& ...

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

JavaScript Functions Not Being Executed by Onclick Event in Internet Explorer 8

When a user clicks, I need two functions to run. This works in Firefox and Chrome, but not in IE8. The first function should display a modal (indicating that the form is being saved, although it's not showing up) while the second function saves the f ...