There seems to be an issue with my JavaScript module as it is displaying an error of "

Within my js file, I have the following code snippet:

;
var tracker = (function () {

    var _track = function(userId, atts) {
        alert(userId);
    };


    return {
        track: function (userId, atts) {
            _track(userId, atts);
        }
    }
}());

I'm implementing the javascript using a common pattern observed in other services:

<script>
(function(w, d, js) {
    var f = d.getElementsByTagName('script')[0],
        s = d.createElement('script');
    s.async = true;
    s.src = js;
    f.parentNode.insertBefore(s, f);
})(window, document, '//localhost/WebApp1/Assets/tracker/tracker.js');

var userAtts = {
        'foo': 1,
        'bar': 2,
        'some-invalid-identifier': 3
    };

    $(document).ready(function() {
        tracker.track(3213, userAtts);
    });
</script>

Despite this setup, an error message appears:

(index):107 Uncaught ReferenceError: tracker is not defined.

The root cause of this issue eludes me.

Answer №1

Before using the tracker function, it is important to ensure that the external JS is fully loaded.

An easy method to achieve this is to continuously check if the tracker is available:

var trackerLoadedListener = setInterval(function(){
  if (typeof tracker !== 'undefined'){
    clearInterval(trackerLoadedListener);
    // Your function call / code here, should only run when tracker is ready
  }
}, 500)

Another approach would be to implement a callback in the script addition function. However, it's uncertain if there may be a delay between adding the script and making it usable in your code.

Answer №2

There is another approach to calling tracker when the script is loaded by adding a handler to the onload event, and passing this directly, or using promises.

For instance:

var trackerPromise = (function(w, d, js) {
  return new Promise(function(resolve) {
    var f = d.getElementsByTagName('script')[0],
      s = d.createElement('script');  
    s.async = true;
    s.src = js;
    s.onload = resolve;
    f.parentNode.insertBefore(s, f);

  });
})(window, document, 'script.js');

and replace jQuery's ready function with this

trackerPromise.then(function() {
  tracker.track(3213, userAtts);
});

Sample plunkr

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

Parsing JSON or eliminating double quotation marks in data acquired from a model or database within the Rails framework

foo.html.erb <script type="text/javascript"> var all_user_data = <%= @user.all_user_bar_chart.to_json.html_safe) %>; </script> abc.js $(function () { if ($("#foo").length > 0){ var user_charts = new Highcharts.Chart({ ...

Having trouble with AngularJs 1 functionality?

Having trouble fetching data from a JSON file. I've tried all available options, but nothing seems to be working. Not sure if I need to import something else. The JSON file is located at the same level as the index file. Any help would be much appreci ...

Three.js - Expanding Your Field of Vision

How can I determine the width of the visible portion of a scene being rendered? For instance, if there is a mesh with a width of 100 units but is being displayed on the screen with a specific level of zoom, how do I calculate the actual width of the mesh ...

Minimize the count of switch cases that are not empty

How can I optimize the number of cases in my switch statement to align with SonarQube recommendations? Currently, I have 37 cases in a switch statement, but SonarQube recommends only 30. I believe that my code is functioning correctly, and the issue lies ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

I am experiencing issues with my asynchronous request in Express

I'm currently in the process of transitioning my requests to async calls to prevent them from blocking. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? er ...

Tips for eliminating flicker upon the initial loading of a webpage caused by dynamic changes in CSS styles through JavaScript

Struggling with the load order of my CSS and JavaScript... Currently, I have a div with a blue background that is styled to appear sliced diagonally. However, upon initial page load (or CTRL+SHIFT+R), there's a brief moment where the slice effect doe ...

Steering clear of repeating evaluations and dynamically unloading objects requested with `require` is important

I'm currently delving into the intricacies of the nodejs module system. Among the resources I've come across so far are: https://nodejs.org/api/modules.html These readings have shed light on a few aspects, but I still have some lingering ques ...

What is causing the failure of this form validation when checking for empty input values?

Within my code, there exists a group of radio buttons labelled fitness, with six available options ranging from values 1 to 6. I've created a function to verify if the user has indeed selected one of the aforementioned options: function validateF ...

I am experiencing an issue in Next.js where the styling of the Tailwind class obtained from the API is not being applied to my

Having an issue with applying a bg tailwind class to style an element using an API. The class text is added to the classlists of my element but the style doesn't apply. Below are the relevant code snippets: //_app.js component import "../index.css"; i ...

Angular JS - Establishing a Connection to Woocommerce OAuth v1

I'm having trouble authenticating myself with the rest service. I attempted to use this library to generate all the necessary parameters as mentioned here, and I constructed the request like this: $scope.oauth = new OAuth({ consumer: { p ...

Error: SignalR Server has sent a "Close" message

I have been struggling with this error for quite a while. I am trying to make signalr listen to my 2 methods. It works perfectly when I comment out the (this) methods. However, it does not work. Can anyone help me figure this out? Sometimes I can retrieve ...

Utilizing ASP.NET to call a JavaScript function

I am currently working on an ASP.NET page that is written in VB.NET and I am attempting to incorporate JavaScript into it. The goal is to take the value from one listbox and insert it into another listbox. One of the challenges I'm facing is the use o ...

What steps should be taken to develop a Hybrid Mobile App concept?

We are currently developing our first hybrid mobile application with a monetizable idea in mind. After conducting some research, it seems that to reach our end goal we will need: A Front End UI Framework: options include Ionic or AngularGap (although d ...

Pass information from JavaScript to PHP using Ajax without any need for converting data types

I have a JavaScript object that I need to send to PHP using AJAX. I want to ensure that the data types in the object are preserved when sending it, such as NULL remaining as NULL and boolean values as booleans. Here is what I have tried: var js_object = ...

Steps to deactivate a div in React after a single click

When you click the "show" button for the first time, it displays "hello world" correctly. However, if you click on show again, it should not work. How can I make it so that after one click, it does not hide hello world if you click again? I've tried u ...

Invoking a PHP class through an AJAX response handler code

I'm attempting to access a PHP-File using AJAX. When I use a basic PHP-File like this: <?php header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: must-revalidate, pre-check=0, no-store, no-cache, max-age=0, pos ...

Tips for developing a dynamic form with Vue.js using Vuetify

I am in the process of creating a dynamic form that needs to function properly. Within my array of competences, there is a skills array. Each skill within a competence needs to be evaluated, requiring a corresponding answer. My setup involves a v-stepper ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...