What is the method to retrieve the name of the current JavaScript file being run?

I've been working on a project with multiple features, and I want to organize each feature in separate JavaScript files for easier loading. I'm developing a function to handle the loading and execution process efficiently. The function should load and execute the JavaScript file if it's not already loaded or simply execute it if it is. One idea is to require two parameters - the file name and the entry point function's name. The function would then check if the script is loaded, execute the entry point function if so, or load the script and execute the entry point function upon onload event if not. However, this approach may become cumbersome as more functions are added, risking duplication of function names. A cleaner solution would be to assign a single "main" function to all entry points and associate it with its corresponding script DOM object, like this:

Loaded module:

function(){
   function main(){
      .
      . some code here
      .
   }
   Install(getThisFileName(),main);
}();

Main module:

function Load(fn){
var el,ff,i
   el = document.getElementsByTagName("script");
   ff = "http://"+window.location.host+fn;
   for(i=el.length-1;i>=0;i--){
      if(el[i] && el[i].src==ff){
         el[i].Main();
         return;
      }
    }
    el = document.createElement("script");
    el.type = "text/javascript";
    el.src = ff; 
}

function Install(ff,ep){
var el,i;
   el = document.getElementsByTagName("script");
   for(i=el.length-1;i>=0;i--){
      if(el[i] && el[i].src==ff){
         el[i].Main = ep;
         ep();
         return;
      }
   }
}

However, I'm unsure how to retrieve the name of the executing JavaScript file. Any suggestions?

Answer №1

A simple solution would be to start by including the following:

var currentScriptFile;
function getCurrentFileName() {
  return currentScriptFile;
}

Then, at the beginning of each file, add this snippet at the top:

currentScriptFile = 'thisScriptFile.js';

This method works well if your code runs sequentially. Once all files are loaded, currentScriptFile will always hold the name of the last file.

Another approach is to set currentScriptFile at the beginning of each function within each file. While that specific function is being accessed, you can use getCurrentFileName() to retrieve the name of the last or current file being executed.

However, keep in mind that this might introduce some additional overhead to your code.

Answer №2

If you're looking to collect all scripts in an array, the code snippet below will help:

let allScripts = Array.from(document.getElementsByTagName("script"));

The script representing the current file is always at the end of the array. To access it, use allScripts[allScripts.length-1]. You can then extract the src attribute from this script element.

Note: This method may not be effective for asynchronous implementations.

Answer №3

If you want to manage your scripts in a global way, one approach could be to create an object for them:

var myScripts = {
    addScript : function(filename) {
        myScripts[filename] = {
            loaded : true,
            executed : false
        }
    }
}

Then, in each file, include the following line at the very end:

myScripts.addScript('myFilename.js');

After the script has finished executing, set its status like this:

myScripts['myFilename.js'].executed = true;

Whenever needed, you can check the status of any script by looking into the myScripts object.

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

What is the process for incorporating a collection in Mongoose?

Trying to clear the Users collection before and after tests: before(function(done) { mongoose.connection.collections['users'].drop(function(err) { mongoose.connection.collections['users'].insert(user, done); }); }); after(func ...

Error: Unable to use the property 'basename' in the destructured object from 'React2.useContext(...)' because it is null

After a long break from working with React-Router, I'm diving back in with v6 for the first time. The tech stack of my application includes: Vite React Material-UI My troubleshooting steps so far have included: Searching online resources Revisiting ...

Invoking an Angular function with jQuery when a button is clicked

I am trying to trigger a method in an Angular controller using a jQuery button click event. Here is the HTML code snippet: <div class="actionBar"> <select class="select select-primary form-control" id="ClassificationS ...

unable to record the input value in jquery

Snippet for HTML code: <div id="Background"> <input id="search-Bar" type="text"> <button id="SearchButton">Search</button> </div> var name = $("#search-Bar").val(); $("#SearchButton").on("click", function() { co ...

Adding Roles Using Discord.js - A Simple Guide

I'm currently working on a Discord bot using Discord.js, and I am trying to implement a feature where users can use a command to assign themselves a role. However, despite my best efforts, I am unable to get this functionality to work. In my bot' ...

Vue components fail to display properly when transitioning between routes in Vue (version 3) using the Vue Router

Just diving into VueJS version 3 and vue-router. Despite my efforts to troubleshoot by consulting Stack Overflow and Google, the issue remains unresolved. I have defined two routes: /login /admin/index The Problem: While the login route ...

The error seems to vanish when commenting out the following div structure

Since upgrading to Angular 5, I've been encountering the following error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: undefined'. Current value: 'ngIf: null&apo ...

"Ionic offers a seamless integration of both side menu and tabs for enhanced navigation

I am working on implementing a sidemenu and tabs on the same screen in my Ionic app project. Currently, it is almost working, but I need the bottom tabs to be visible at all times while also being able to navigate to other views from the sidemenu without ...

How can I make an image the background on a webpage when clicking the mouse?

I find myself in a predicament without any code to guide me. The idea seems simple - I desire the ability to select an image from a collection and set it as the background image for the webpage. While I understand that JavaScript is essential for this tas ...

Ways to toggle the sliding of text on and off an image?

After spending some time experimenting with my code, I managed to get it working. Essentially, when a user hovers over an image, text now appears over the image. Since this is a gallery, I had to utilize $(this).children in order to target and display the ...

What is the best way to incorporate data from my API into my component?

App.js import { Text, View, Button, FlatList } from 'react-native'; import { useEffect, useState } from 'react'; import * as React from 'react'; const API = 'https://randomuser.me/api/users/'; const User = (props) ...

New in the world of JavaScript: A method that replicates the functionality of jQuery's

Take a look at this JSFiddle example: https://jsfiddle.net/1a6j4es1/1/ $('table').on('click', 'td', function() { $(this).css('background', 'green'); }); How can you rewrite this code using plain JavaS ...

"Concurrency issues arise when using multiple AJAX calls in jQuery, causing confusion with

This piece of JavaScript code involves a series of AJAX calls to my FastCGI module in order to retrieve certain values. However, there seems to be an issue where the value intended for display in "div2" is ending up in "div1", and vice versa, ultimately ca ...

Tips for showcasing a table generated from various input types on a separate page after pressing the submit button

After creating two JavaScript functions, I am eager to utilize both of them upon pressing the submit button on my form. The first function is already integrated into the submit button and activates a paragraph display upon submission. Now, I intend to sh ...

Encountered a setback while trying to add information to a MySql database through Express

When I try to execute an insert query on a database, it throws the following error: code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versio ...

Conceal a row depending on the value in a specific column

After reviewing the data in the table provided: +-----------------------+-----------------+---------------+ | 212 | fred | red | +-----------------------+-----------------+---------------+ | 230 ...

Canvas connectives (HTML5)

I have successfully implemented a user interface, but I am experiencing lower FPS during certain moments. After conducting a performance test with Firefox, I have realized that these FPS drops occur when the browser re-calculates CSS. The CSS recalculatio ...

Presentation: Troubleshooting Ineffective CSS3 Transitions

I have created a basic slideshow that can accommodate multiple images. Clicking on an image should move to the next slide, and once the last image is clicked, it should loop back to the first slide. The functionality of transitioning between slides seems ...

How can I reference MyClass.new as a method in Typescript?

Within my code, I have an array of objects and each object is structured like this: { id: 'string', name: 'string' } There's a class defined as follows: class User { constructor(obj: Record<string, string>) { Object.as ...

Is there a method for dynamically loading angular directives?

Check out this quick demo: http://jsfiddle.net/aSg9D/ Essentially, both <div data-foo-{{letterA}}></div> and <div data-ng:model="foo-{{letterB}}"></div> are not being interpolated. I'm trying to figure out a way to dynamical ...