Is there a way to improve the efficiency of this JavaScript code?

I'm looking to optimize the code below in order to replace each link's href querystring with the current page URL's querystring if the current page URL has an argument 'myid1' or 'myid2' in the querystring. I want this script to execute as quickly as possible. Any assistance would be greatly appreciated. Thank you in advance :)

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>

<script type="text/javascript">
$(function() {
    var requestid = gup('myid1');
    if (requestid) {
        $("a.rewrite").each(function() {
            var base = this.href;
            var pos = base.indexOf("?");
            if (pos != -1) {
                base = base.substr(0, pos);
            }
            this.href = base + "?myid1=" + requestid;
        })
    }
    var requestid2 = gup('myid2');
    if (requestid2) {
        $("a.rewrite").each(function() {
            var base = this.href;
            var pos = base.indexOf("?");
            if (pos != -1) {
                base = base.substr(0, pos);
            }
            this.href = base + "?myid2=" + requestid2;
        })
    }
})

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
</script>

<a href="http://www.website.com/?someid=1234" class="rewrite">Hyperlink</a>

Answer №1

$(function() {
    var id1 = gup('id111');
    var id2 = gup('id222');

    if (id1 || id2) {
        $("a.update").each(function() {
            var url = this.href;
            var index = url.indexOf("?");
            if (index != -1) {
                url = url.substr(0, index);
            }

            if (id1){
                this.href = url + "?id111=" + id1;
                if (id2){
                    this.href += "&id222=" + id2;
                }
            } else {
                this.href = url + "?id222=" + id2;
            }

        })
    }

});

Answer №2

There are two key inefficiencies in the provided code:

  1. Unnecessary looping. The code loops through each anchor with the class "rewrite" for every querystring match, which can be optimized into a single loop;

  2. Repeated calculation of regular expression matches. The regex pattern is executed multiple times within the code when it could be minimized to just one calculation.

The optimal solutions include:

  1. Store the window.location.href data in a variable for future reference;

  2. Consolidate multiple loops into one and handle all replacements within that single loop.

Here's the improved version of the code:

// First, retrieve the query string parameters as key-value pairs from window.location.href, similar to the gup function.

// This snippet captures the ?key1=value1&key2=value2 pairs and stores them in a JavaScript Object {'key1': 'value1', 'key2':'value2'}
var queryString = {}; 
var queryStringPattern = new RegExp("([^?=&]+)(=([^&]*))?", "g");
window.location.href.replace(
    queryStringPattern,
    function($0, $1, $2, $3) { queryString[$1] = $3; }
);

// Next, iterate through all anchors with the class "rewrite" and perform the necessary replacements.

$("a.rewrite").each(function () {
  this.href.replace(
    queryStringPattern,
    function ($0, $1, $2, $3) {
      return queryString[$1] ? $1 +  "=" + queryString[$1] : $1 + '=' + $3;
    }
  )
});

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

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

I am exploring directories on my server but encountered a restriction while using $.ajax

I am currently working on designing a basic webpage using p5.js, where I have implemented a script to search for images within folders and display them all on a single page. To facilitate this process, I am utilizing the $.ajax({}); function to check ...

Concealing Nested Div Elements

Can someone help me figure out why my code is not hiding the two divs within my content div? I need assistance checking my code to see what's causing the issue. Thank you! I have made some edits to my code. Currently, both forms appear under the "War ...

Trouble with AJAX not properly fetching PHP JSON response

I recently encountered an issue with my jQuery AJAX request that sends user input to a PHP file. Initially, the code worked perfectly fine but adding "dataType: 'json'" caused it to malfunction. Here's how I set it up: $.ajax({ url: url ...

Ways to resolve nested structure issues within a bookshelfjs transaction

I'm looking to optimize my code by updating multiple tables in a database using a single bookshelf transaction. I'm relatively new to node.js and struggling with promises, resulting in a messy nested structure. Any suggestions on how to refactor ...

The customizing of font color with Fancytree's "extraClasses" feature is not being properly applied

In my web application, I have a tree that utilizes fancytree. Everything is functioning properly, except for the fact that I need to set the font color to red for certain nodes. I have implemented the use of extraClasses in my JSON, which is successfully a ...

Is the append() function malfunctioning in jQuery?

Why is it copying two lines when I only want one line to be cloned on button click? Is there a way to make sure that only a single line is copied each time the button is clicked? Here is my code: $(function() { $('.add-more-room-btn').clic ...

Tips for streamlining the filter function using replace and split:

Currently, I am utilizing a filter function alongside replace() and split(). Here is the code snippet: jQuery('table .abc').filter((i, el) => jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] + &ap ...

Ways to alter the appearance of individual characters in the text input

My latest project involves dynamically changing the CSS styles of each individual character in a given text input. For example, if the user types "Stack" into the input field, I want the 'S' to appear in red, 't' in blue, 'a' ...

Issue with JQuery Event Listener on Canvas Subelement not functioning

I encountered an issue while trying to implement a custom crop rectangle on a canvas using JavaScript. I created a function that, when called, should add a child node to the existing canvas and use JQuery listeners to draw the rectangle. However, although ...

Ways to verify if element has been loaded through AJAX request

I am trying to determine if an element has already been loaded. HTML <button>load</button> JS $(document).on('click','button',function () { $.ajax({ url: 'additional.html', context: document ...

How can a list be returned from an async callback in NodeJS?

Essentially, I am performing a database query to retrieve all posts with a specific id, then adding them to a list before returning. However, the list is being returned before the callback function has finished executing. How can I ensure that the list is ...

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...

Error alert: The $ symbol is not defined

I followed a tutorial to create an auto-advancing slideshow in JavaScript/jQuery and it worked perfectly on jsfiddle. However, when I transferred everything to Dreamweaver, it stopped functioning. I have triple-checked that all the necessary files are link ...

Building a Database in a Node.js Express Application Using Jade and JavaScript

UPDATE After conducting extensive research, I have discovered that the web application utilizes the node-db-migrate package. Within the migration folder, there are two migrations containing table creations. As I recently git cloned the project, it is evid ...

Is it possible to convert HTML to PDF on the server?

A PDF file is being created from an HTML file using the princexml pdf converter package. The data for the HTML file is provided by the server. In the browser, jQuery is used to generate the input string (HTML code) for creating the PDF. Once the input stri ...

What is the best way to efficiently set up a scrolling text ticker for repeated use?

I am currently utilizing GreenSock/TweenMax for the creation of scrolling text, inspired by the design seen on this webpage: If you're interested in learning more about Greensock and its capabilities, take a look at their documentation here: While I ...

Manipulating State in React: How to add a property to an object within an array within a component's state

Currently, I am retrieving an array of objects stored in the state, and I am attempting to include a new property to each of these objects. However, I am encountering a problem where even though I can see the new property being added to each object, when ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...