Injecting Angular into an Immediately Invoked Function Expression (IIFE)

I have come across the following discussions:

Exploring the advantages of enveloping angular controller/service/factory declarations in an anonymous function

Analyzing the benefits of wrapping an angular javascript file with "(function() { ....[js code here]...... })();"

However, none directly address my query. In the context of wrapping JavaScript in IIFE blocks, two common patterns can be observed:

(function (window, angular, undefined) {
'use strict';

angular.doSomething();

// more code here
})(window, window.angular);

and also this:

(function () {
'use strict';

angular.doSomething();

// more code here
})();

While it is evident that 'angular' is globally defined, I am curious about the advantages and disadvantages of the first approach over the second. Since JavaScript passes 'angular' by reference regardless, are there any performance improvements, scope security enhancements, or is it primarily beneficial for code minification?

Answer №1

Among the items on your list, only code minification purposes are applicable; the other two are not.

There is one additional benefit to consider. Imagine a scenario where a document loads angular, followed by your script, and then another script. The final script could potentially alter the global namespace of `angular` at a later time, introducing a newer version or even something malicious, causing unexpected behavior in your code.

Take a look at this example:

////////////////////
// 1. Angular is loaded directly.

////////////////////
// 2. Your code:
(function() {
  'use strict';
  
  window.setInterval(function() {
    console.log(angular.version.full);
    document.write(angular.version.full + "<br>");
  }, 1000);

  // more code here
})();

////////////////////
// 3. Another snippet/library:
window.setTimeout(function() {
  window.angular = { version: { full: "muhahaha!" } };
}, 2500);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

The output would be different with an alternative approach:

////////////////////
// 1. Angular is loaded directly.

////////////////////
// 2. Your code:
(function(window, angular) {
  'use strict';
  
  window.setInterval(function() {
    console.log(angular.version.full);
    document.write(angular.version.full + "<br>");
  }, 1000);

  // more code here
})(window, window.angular);

////////////////////
// 3. Another snippet/library:
window.setTimeout(function() {
  window.angular = { version: { full: "muhahaha!" } };
}, 2500);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

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

Issues with displaying data in Angular ChartJS are troubling users

Currently utilizing Angular 6, my goal is to incorporate a Chart.js line chart. Essentially, I am fetching two arrays from my API: one named weight_data and the other named weight_date, which I then utilize for the chart. After receiving the arrays from t ...

Issue with ngModelChange and change events not functioning properly in Internet Explorer 11

Within a text input field, I have implemented single-way binding in addition to utilizing a number formatter pipe. I have also set up an (ngModelChange) event handler to remove any commas that are added by the number formatter, and a (change) event to tri ...

Encountered an issue when trying to add content following $http .then()

Hi there, I am currently using AngularJS $http to fetch JSON data. Here is the JSON Data: {"Data":["index":[{"Name":"append_here_1"},{"Name":"append_here_2"}]]} In my App.js file: var app = angular.module('app', []); Request.js: app.service ...

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

Angular UI-Select's issue with duplicating tags while adding objects for tagging functionality

I have implemented the ui-select library to enable the "Tagging" feature in my project. Currently, I am utilizing an Array of objects where each object contains an id and a name. The functionality is working as expected. However, when a user types in a n ...

Uploading Files with Ajax in Asp.Net Core

Hey there! I'm facing an issue while attempting to upload a file using ajax from the client side to the server side (asp.net core) controller as I keep getting a null value. Below are my HTML and JavaScript codes: <input type="file" id="myfile" ...

Tips for encoding UTF characters with JSON.stringifyendcode:

Currently, I am developing a JavaScript script that is executed using windows cscript.exe. The purpose of my script is to load a JSON object from a file, add a parameter, and then save it back to the file (I am utilizing the json2.min.js implementation). ...

When attempting to use a context, the type '...' cannot be assigned to type '...'

In my Next.js project, I am utilizing createContext to implement a dark mode button. The original jsx file for this functionality is called ThemeContext.tsx, and I am currently in the process of converting it to TypeScript. "use client"; import ...

The console.log function cannot be used within the app.get method, yet it functions correctly when placed outside of it

Having a persistent issue that I just can't seem to solve. Whenever I attempt to use the console within my app.get method, logging or calling other methods related to console simply doesn't work for me. I've gone as far as reinstalling nodej ...

Having trouble getting the CSS in my tab control to work consistently across all browsers. Any tips on how to troubleshoot and fix this issue?

When using CSS, there are essentially two classes involved. One controls the default color of tabs, while a "selected" CSS class is added through JavaScript when a tab is clicked. The functionality works perfectly, but unfortunately, the dynamic CSS only ...

Storing image data using JavaScript

I am in the process of creating a 360-degree viewer that utilizes raster tiles (leaflet) and requires over 85,000 images for each view. In order to enhance the viewer's performance, I am attempting to cache all of these images. However, I keep receivi ...

Express Angular Node Template Render throwing an error: module 'html' not found

I am currently in the process of creating a web application using AngularJS with ui-router for routing via $stateProvider, ensuring that only the specified states are displayed in the ui-view. In my server.js file, I have set up an initial framework such ...

What is the best way to implement a hover feature on a Vue / Vuetify Autocomplete dropdown list?

I'm not very experienced with Vue and I'm finding it a bit complex to grasp. Perhaps you guys can provide the "best practice" or most efficient solution for my issue: I have an autocomplete dropdown box. When expanded, it shows a list with click ...

Determining the live total number of Protovis Sparkbar instances

I am currently working on a project where I need to show the ratings and corresponding dates (in string format) from a JSON file in tipsy tooltips. The data consists of a list of dates and ratings. For example: var data = [{"dates":["2010-07-01","2010-07 ...

Implementing the requiredUnless validator of vuelidate for checkboxes: A step-by-step guide

When utilizing Vuelidate, the 'required' validator now accepts boolean 'false' as a valid value. To enforce required validation for checkboxes, you must use 'sameAs' such as sameAs: sameAs( () => true ). How can 'requi ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

Getting rid of unwanted scrollbars in a breeze

I am facing an issue with two nested divs that have the same height settings. The outer div has a max-width/height constraint along with overflow auto, causing scrollbars to appear when the inner content exceeds its dimensions. However, even if I resize ...

Revise the model and execute the function

When updating my model object, I am looking for a way to trigger a specific method. I have considered options such as: findOne modifying my properties calling the method on the object save Is there a way to achieve this using update or findOneAndUpdate ...

Is it possible to embed an Angular application within a specific DOM element?

I am the proud owner of two web applications. One is a traditional JavaScript web app, while the other is built on Angular (Version 10). My goal is to load the Angular app inside a DIV container after the JavaScript app has finished load ...

Trouble with AngularJs 1.x causing Bootstrap4 menu toggle collapse to malfunction

Issue with Navbar toggle menu not closing properly. I have attempted the solutions provided here and others in an effort to fix this bug. However, none of them seem to work for me. Here is a snippet of my code: <nav class="navbar navbar-expand-lg ...