Guide to adding a script with a relative path to an HTML file using JavaScript

Encountering an issue while attempting to inject a script into an HTML page using JavaScript. The script needs to have a relative path similar to what is in the cshtml file:

<!DOCTYPE html>

<html>
<head>
    @{
        if (Request["debug"] != "false")
        {
            <script src='~/Scripts/script-first-debug.js'></script>
            <script src='~/Scripts/script-second-debug.js'></script>
        }
        else
        {
            <script src='~/Scripts/script-first.js'></script>
            <script src='~/Scripts/script-second.js'></script>
        }
    }

</head>
<body>
    @RenderBody()
</body>
</html>

This is a snippet of my TypeScript file where I have moved this .NET logic from the cshtml file:

var scriptFirst = document.createElement('script');
var striptSecond = document.createElement('script');

scriptFirst.type = 'text/javascript';
striptSecond.type = 'text/javascript';

scriptFirst.src = this.debug ? '/Scripts/script-first-debug.js' : '/Scripts/script-first.js';
striptSecond.src = this.debug ? '/Scripts/script-second-debug.js' : '/Scripts/script-second.js';

$('head').append(scriptFirst).append(striptSecond);

Everything works fine on localhost, but when I deploy this code to my production application instance, I encounter an issue. The production application adds some string to the address. For example:

On localhost, the path to script-first.js is: https://localhost:80/Scripts/script-first.js

On production, the path to this file becomes:

Any suggestions on how to handle this issue? I've searched for solutions on Stack Overflow and other platforms without much success so far.

Answer №1

Your specified path directs to the root folder (DOCROOT/document root) hosted on www.myproblematicapplication.com. However, the files are not located within that particular folder. To resolve this issue, assuming that the files are in the same directory as your typescript file which includes them in the application:

Modify:

'/Scripts/script-first-debug.js' 

To:

'./Scripts/script-first-debug.js' 

in all instances of URLs.

Take note of the preceding dot. This indicates "locate these files in the same directory relative to this specific file".

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

Incorporate JavaScript data into your Laravel project

I am having an issue with adding form data to a database using JavaScript. The postData is correctly being read as I can see in an alert message, but the URL is not executing. I have tried it with both 'donorlist' and '/donorlist'. $(d ...

jQuery scrollTop(0) leading to unusual scrolling patterns

Every time I click on a button, a modal window appears with a fading effect: $('.display-all-comments').fadeIn(300); $('.display-all-comments').scrollTop(0); If I remove the scrollTop(0), the scrolling works as usual. To better illust ...

Combining multiple jQuery selector objects into one jQuery object

How can I merge two jQuery selectors into one jQuery object? I attempted to use $("#selector","#selector"), but it didn't work and just returned blank. Are there any built-in methods that can help me accomplish this? Is there a way to do it like thi ...

AngularJS: Modifying the template in a Directive with scoped attribute dependencies

As I delve into customizing a template within a directive and incorporating references to attributes in the parent scope, I find myself navigating through the Angular framework as a newcomer. My journey has led me to leaning on Customizing the template wit ...

Using the datepicker class in an input field causes issues with the functionality of the bootstrap datepicker, specifically the autoclose, endDate, and startDate properties do not function as

I'm facing an issue with my code when I add the datepicker to the input field's class. JS $(document).ready(function () { $("#ActionDateInput").datepicker({ autoclose: true, endDate: new Date() }); }); HTML <input type= ...

jQuery Form: Despite the Ajax response being visible on the page, it does not appear in the source code

Utilizing Jquery Form for an Ajax image upload. This is the relevant HTML code: <div class="input_con imageupload_con"> <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"> < ...

Calculate the pixel distance between various divs by measuring the horizontal distance from the left border to the right

I am trying to find the precise distance between : #main div left edge to the first div with class="b" between the first div with class="b" to the second div with class="b" It's worth noting that the divs may be arranged randomly and could have fix ...

Which architectural style is best to master for developing exceptional JavaScript software?

My familiarity with Model-View-Controller runs deep, having worked with it for years in server-side development using languages like PHP. Now, I find myself diving into JavaScript and embarking on a large project that utilizes SVG, Canvas, and other moder ...

Issue encountered during app creation using the command line interface

After successfully installing nodejs and checking the versions of nodejs, npm, and npx, I proceeded to run the command npm install -g create-react-app which executed without any issues. However, when I attempted to create a new React app using create-react ...

Disabling the last control in a formGroup when sorting an array with Angular

I am facing an issue with sorting an array based on a numeric control value inside a formGroup nested in another array: const toSort = [ ['key2', FormGroup: {controls: {order: 2}}], ['key1', FormGroup: {controls: {order: 1}}] ] ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...

I am in need of a blank selection option using an md-select element, and I specifically do not want it to be

I'm currently utilizing Angular Material with md-select and I am in need of creating a blank option that, when selected, results in no value being displayed in the select dropdown. If this blank option is set as required, I would like it to return fal ...

Prevent callback function execution in JavaScript

Users have the ability to select a month by clicking +1 month or -1 month. Each click triggers a loop based on the number of days in the chosen month. Within the loop, a function is called to fetch data through an $http request. The issue at hand is as ...

Substituting generic type in inherited class method results in error message: "Property 'x' in type 'y' cannot be assigned to the property with the same name in the base class 'Parent'."

Here is the code snippet I am working with: class BaseModel { protected getAttribute<T extends BaseModel>(): keyof T | null { return null; } } class Payment extends BaseModel {} class Item extends BaseModel {} class Sale extends BaseModel { ...

Issue: TypeError - The function addTicket is not recognized as a valid function. Utilize the useState hook within the modal component

I'm currently facing some challenges with the implementation of the useState hook and I am struggling to understand why it is not working as expected. My project involves creating a basic ticket system where users can click on a button to open a moda ...

The fastest method for finding the longest palindrome subsequence within a given string

I've been working on creating a function that can identify the longest palindrome subsequence within a given string. After experimenting with dynamic programming, I came up with the code snippet below: function findLongestPalindrome(str) { let lengt ...

The type 'string' cannot be assigned to the specified type

I'm attempting to establish a constant that can only contain two specific values as displayed in the code snippet. The variable state.lang is already ensured to be type-safe with a value of either en or ar. const keyname: 'owner_name_en&apos ...

The initial value for React input is vacant and is not capturing either the state or the prop value

After utilizing Vue for an extended period, I have now transitioned to React. To practice, I am attempting to convert some basic Vue components into React. My initial Vue code was simple as shown below: <template> <div> <h1>Hello { ...

No cookie found in the system

Attempting to create an effect using bloom and shaders in post-processing. However, encountering an error in the console with a blank white screen. I have tried clearing cookies, caches, and even running this in incognito mode, but it's still not work ...

Is null a type of object in JavaScript?

As I delve into the realm of JavaScript data types, I stumbled upon a peculiar discovery: > typeof null "object" > null instanceof Object false At this point, I am baffled as to how to make sense of this phenomenon. I was under the assumption that ...