delayed load time for js file

so i made a script to change the css file linked depending on time of year. however the load time is too slow when changing page and refeshing, causing my page to load without css for a few seconds. Any thoughts on how to do this? i tried defer and async and changing the listed order of the linked files but it doesnt either, i have a feeling my js code is too slow and changing the href attribute may be an inefficient way for it to work. Any help would be most appreciated

aformentioned html file

<!DOCTYPE html>
<html>
  <head>
  
      <script type="module" src="localimports/scripts/script_for_site_themes.js" type="text/javascript" ></script>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Index</title>
    <link rel="stylesheet" href="localimports/css/style.css">
    <script src="localimports/navbars/header.js" type="text/javascript" defer></script>
    <script src="localimports/navbars/footer.js" type="text/javascript" defer></script>
        <link id="sitebirthday" rel="stylesheet" href="">
    <link id="october" rel="stylesheet" href="">
    <link id="christmas" rel="stylesheet" href="">
    <link id="newyear" rel="stylesheet" href="">
    <link id="normal" rel="stylesheet" href="">


    
    

  </head>
  <body>
  

    <header-component>
    </header-component>
    <main>


below is the linked js file named script_for_site_themes.js that i call on to get my css file


 setInterval(function () {
        var date = new Date();
        var isodate = new Date().toISOString()

        if (date.getMonth()  === 11 && date.getDate()  === 12) {

                                    document.getElementById("sitebirthday").href="https://www.google.co.uk";



        }


        if (date.getDate()  === 9 ) {

                                    document.getElementById("october").href="https://www.google.co.uk";

        }

         if (date.getMonth()  === 11 ) {

                                    document.getElementById("christmas").href="https://www.google.co.uk";



        }


         if (date.getMonth()  === 0 ) {

                                    document.getElementById("newyear").href="https://www.google.co.uk";

        }
        
        
        
         else {

                                    document.getElementById("normal").href="../localimports/css/templateofcssthemes.css";

        }


        








    }, 1000)
    
    





</main>  <br>

<footer-component></footer-component>

Why is this AudioWorklet to MP3 code producing different results on Chromium and Firefox?

I’m running the same code on Firefox 125 and Chromium 124.

The code run on Firefox produces a Blob that is an encoded MP3 file – after chopping up whatever audio is being played in Firefox while the audio is finalizing encoding.

The Chromium version produces an MP3 that is full of glitches, clipping, and plays back faster.

Here’s a link to a ZIP file containing the result examples https://github.com/guest271314/MP3Recorder/files/14625262/firefox125_chromium124_audioworklet_to_mp3.zip.

Here’s a link to the source code https://github.com/guest271314/MP3Recorder/blob/main/MP3Recorder.js.

In pertinent part:

// https://www.iis.fraunhofer.de/en/ff/amm/consumer-electronics/mp3.html
// https://www.audioblog.iis.fraunhofer.com/mp3-software-patents-licenses
class MP3Recorder {
  constructor(audioTrack) {
    const {
      readable,
      writable
    } = new TransformStream({}, {}, {
      highWaterMark: 65536,
    });
    Object.assign(this, {
      readable,
      writable,
      audioTrack,
    });
    this.writer = this.writable.getWriter();
    this.audioTrack.onended = this.stop.bind(this);

    this.ac = new AudioContext({
      latencyHint: .2,
      sampleRate: 44100,
      numberOfChannels: 2,
    });

    const {
      resolve,
      promise
    } = Promise.withResolvers();
    this.promise = promise;

    this.ac.onstatechange = async (e) => {
      console.log(e.target.state);
    };
    return this.ac.suspend().then(async () => {
      // ...
      const lamejs = await file.text();
      // const {lamejs} = await import(url);
      const processor = `${lamejs}
class AudioWorkletStream extends AudioWorkletProcessor {
  constructor(options) {
    super(options);
    this.mp3encoder = new lamejs.Mp3Encoder(2, 44100, 128);
    this.done = false;
    this.transferred = false;
    this.controller = void 0;
    this.readable = new ReadableStream({
      start: (c) => {
        return this.controller = c;
      }
    });
    this.port.onmessage = (e) => {
      this.done = true;
    }
  }
  write(channels) {
    const [left, right] = channels;
    let leftChannel, rightChannel;
    // https://github.com/zhuker/lamejs/commit/e18447fefc4b581e33a89bd6a51a4fbf1b3e1660
    leftChannel = new Int32Array(left.length);
    rightChannel = new Int32Array(right.length);
    for (let i = 0; i < left.length; i++) {
      leftChannel[i] = left[i] < 0 ? left[i] * 32768 : left[i] * 32767;
      rightChannel[i] = right[i] < 0 ? right[i] * 32768 : right[i] * 32767;
    }
    const mp3buffer = this.mp3encoder.encodeBuffer(leftChannel, rightChannel);
    if (mp3buffer.length > 0) {
      this.controller.enqueue(new Uint8Array(mp3buffer));
    }
  }
  process(inputs, outputs) {
    if (this.done) {
      try {
      this.write(inputs.flat());
      const mp3buffer = this.mp3encoder.flush();
      if (mp3buffer.length > 0) {
        this.controller.enqueue(new Uint8Array(mp3buffer));
        this.controller.close();
        this.port.postMessage(this.readable, [this.readable]);
        this.port.close();
        return false;
      }
      } catch (e) {
        this.port.close();
        return false;
      }
    }
    this.write(inputs.flat());
    return true;
  }
};
registerProcessor(
  "audio-worklet-stream",
  AudioWorkletStream
)`;
      this.worklet = URL.createObjectURL(new Blob([processor], {
        type: "text/javascript",
      }));
      await this.ac.audioWorklet.addModule(this.worklet);
      this.aw = new AudioWorkletNode(this.ac, "audio-worklet-stream", {
        numberOfInputs: 1,
        numberOfOutputs: 2,
        outputChannelCount: [2, 2],
      });
      this.aw.onprocessorerror = (e) => {
        console.error(e);
        console.trace();
      };
      this.aw.port.onmessage = async (e) => {
        console.log(e.data);
        if (e.data instanceof ReadableStream) {
          const blob = new Blob([await new Response(e.data).arrayBuffer()], {
            type: "audio/mp3",
          });
          resolve(blob);
          console.log(blob);
          this.audioTrack.stop();
          this.msasn.disconnect();
          this.aw.disconnect();
          this.aw.port.close();
          this.aw.port.onmessage = null;
          await this.ac.close();
        }
      };
      this.msasn = new MediaStreamAudioSourceNode(this.ac, {
        mediaStream: new MediaStream([this.audioTrack]),
      })
      this.msasn.connect(this.aw);
      return this;
    }).catch(e => console.log(e));
  }
  async start() {
    return this.ac.resume().then(() => this.audioTrack).catch(e => console.log(e));
  }
  async stop(e) {
    this.aw.port.postMessage(null);
    return this.promise;
  }
}

Here’s how I use the code, with setTimeout() included for how to reproduce what I’m getting here for tests:

var stream = await navigator.mediaDevices.getUserMedia({
  audio: {
    channelCount: 2,
    noiseSuppression: false,
    autoGainControl: false,
    echoCancellation: false,
  }
});
var [audioTrack] = stream.getAudioTracks();
var recorder = await new MP3Recorder(audioTrack);
var start = await recorder.start();
setTimeout(() => {
  recorder.stop().then((blob) => console.log(URL.createObjectURL(blob)))
  .catch(console.error);
}, 10000);

What’s the issue on Chrome/Chromium?

Write an algorithm that will output the path while collecting capital letters inside a matrix representing the grid of elements

I have this exercise task where you are required to gather data on a specific path, such as a walking route. You need to follow a
path of characters and collect letters:

● Start at the character >

● Follow the path

● Collect letters

● Stop when you reach the character s

Input: A matrix representing the grid, it can be constant
Output:

  • Path
  • Letters

This is the example

enter image description here

This is the Output:

  • Path @—A—+|C|+—+|+-B-s
  • Letters ACB

This is for the assignment

enter image description here

These are the rules

  • The only valid characters are all uppercase letters (A-Z)
  • Turns can be letters or +

https://codeshare.io/NKoe6V

The output is >—A-@-+s, after the first row it goes straight to the end to “s”

How to change Draggable component’s original position

I’m working with the react-native-draggable component.

return (
    <View >
        <Draggable x={75} y={100} renderSize={56} renderColor='black' renderText='A' isCircle shouldReverse onShortPressRelease={()=>alert('touched!!')}/> 
        <Draggable x={200} y={300} renderColor='red' renderText='B'/>
        <Draggable/>
    <Draggable x={50} y={50}>
        <YourComponent/>
    </Draggable>
    </View>
);

By setting the shouldReverse prop to true, the draggable item smoothly returns to its original position.

However, I can’t seem to dynamically update the “original position” of the draggable item by updating the position.x and position.y values, as in the following code:

    <View style={styles.answerContainer}>
        {answerParts.map((item, index) => (
            <Draggable
                key={item.index}
                x={item.position.x}
                y={item.position.y}
                disabled={item.placed}
                shouldReverse={!item.placed}
                onDragRelease={(event) => onReleaseItem(item, event)}
            >
                <View style={styles.draggableItem}>
                    <Text style={styles.draggableText}>{item.text}</Text>
                </View>
            </Draggable>
        ))}
    </View>

Any thoughts on how I can properly change the original location of a draggable React Native component?

Thanks!
Anson

How to open an EPUB inside of a chrome extension?

I am trying to open an epub file in my chrome extension page (‘dist/epub-viewer.html’) but chrome keeps trying to download the epub instead. I am using manifest v3.

function isEpubUrl(url) {
  return url.toLowerCase().endsWith('.epub');
}

function isEpubViewerUrl(url) {
  const viewerUrl = chrome.runtime.getURL('dist/epub-viewer.html');
  return url.startsWith(viewerUrl);
}

function openEpubInViewer(tabId, epubUrl) {
  const viewerUrl = chrome.runtime.getURL('dist/epub-viewer.html') + '?file=' + encodeURIComponent(epubUrl);
  chrome.tabs.update(tabId, { url: viewerUrl });
}

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.url && isEpubUrl(changeInfo.url) && !isEpubViewerUrl(tab.url)) {
    openEpubInViewer(tabId, changeInfo.url);
  }
});

Is there any way to do this without having to create an additional page where the user can open their EPUB? I have similar code for PDFs which works fine, but for EPUBs chrome keeps trying to download them.

How to loop through all elements that contain a certain class name using Delphi in TMS WEB Core

I have a couple of HTML elements on my page that were created dynamically, so my Delphi form doesn’t know about them (as far as I’m aware), but all of them have a class called “TestingClass”.

I’m able to loop through all of them using JavaScript code within Delphi from my form such as:

procedure TfrmMain.Testing(Sender: TObject);
begin
  asm
    const elements = document.querySelectorAll(".TestingClass");
    elements.forEach((element) => {
        console.log(element);
        // Access each element using the "element" parameter
    });
  end;
end;

And that works, but ideally, I’d like to eliminate the JavaScript code and use only Delphi. What would be the equivalent Delphi code to get all elements on my page with that class and then loop through it?

Note that all of these HTML elements are created dynamically using JavaScript. So they don’t have the form or application as the owner, but they’re all definitely visible on the page and in the DOM.

How to change CSS classes and style for nav tabs after bslib nav_insert?

Currently for the bslib package, a nav_insert() into a page_navbar does not pass along the same CSS classes as it does for a regular tab-pane, as noted in this issue posted to the bslib Github repo.

The reprex provided by the OP is the following:

library(shiny)
library(bslib)

ui <- page_navbar(
  id = 'nav',
  nav_panel('Page 1',
            card("Content 1")))

server <- function(input, output, session) {
  nav_insert(id = "nav",
             nav = nav_panel('Page 2',
                             card("Content 2")))
}

shinyApp(ui, server)

The newly inserted tab “Page 2” does not have the same css classes as the “Page 1” tab, namely html-fill-item html-fill-container bslib-gap-spacing.

Is there a way, perhaps, to add those classes after the insert? I tried using runjs($('[data-value=Page 1]').addClass('html-fill-item')) (and several iterations of it) in the server but that did not work.

A very trivial JSFiddle demo shows the idea of the basic working syntax.

Any ideas would be very much appreciated! Thanks.

how to fix the error that show index.html:1 Uncaught SyntaxError: Unexpected token ‘%’

index.html:1 Uncaught SyntaxError: Unexpected token ‘%’ (at index.html:1:14)

this error show when i change this code

function templateComment(item, postInfo, conditionComment) {
  console.log(conditionComment)
  const comm = `
    <div class="comment pb-1" onclick=${!conditionComment ? `showUserInfo(${encodeURIComponent(JSON.stringify(postInfo))})` : 'showUserInfo(null)'}>
          <div class="pt-1 flex align-items-center justify-content-center gap-3 pb-1">
          ${typeof item.author.profile_image === "string" ?
      `<img src="${item.author.profile_image}" alt="Avatar1" class="img-fluid my-1" style="width: 30px; height: 30px; border-radius: 50% !important;" />`
      :
      `<img src="images/icons8-user-48.png" alt="Avatar2" class="img-fluid my-1" style="width: 30px; height: 30px; border-radius: 50% !important;" />`
    }                     
          <span><strong>@${item.author.username}</strong></span>
          </div>
          <h5>${item.body}</h5>
        </div>
      `;
  return comm;
}
export default templateComment;
 <div class="comment pb-1" onclick=${!conditionComment ? `showUserInfo(${encodeURIComponent(JSON.stringify(postInfo))})` : 'showUserInfo(null)'}>

the error come when i change this line

so what this error mean and how to slove this error ??

How to call Delphi Procedure from JavaScript code in TMS WEB Core?

I want to call/execute a Delphi procedure via my JavaScript code, but I’m not sure how.

I have my procedure declared as a public procedure within my form’s class declaration like this:

TfrmMain = class(TWebForm)
  ...
private
  { Private declarations }
public
  { Public declarations }
  procedure MyDelphiProcedure(MyParam: UInt64);
end;

And then somewhere on my web page, I have an HTML Image with an onClick event attached to it. I’d like to call my Delphi function from that onClick event, but how? This HTML image is not linked to any Delphi component. It’s just a standalone HTML image that is dynamically created using JavaScript.

Just simply doing MyDelphiProcedure(1); fails. Doing this.MyDelphiProcedure(1); also fails.

How can I access my form and call the Delphi function from JavaScript?

generateStaticParams unexpected returns

I’m trying to generate slugs using generateStaticParams in Next but it somehow “chooses” diferent data to return that I want it to.

function generateSlugs(params) return array of slug objects each containing slug and id.

My problem is that generateStaticParams uses id as slug in returned values instead of slug. What could be wrong?

import Gallery from "@/app/components/Gallery";
import ProductDescription from "@/app/components/ProductDescription";
import Navbar from "@/app/layout/Navbar";
import ProductSection from "@/app/layout/ProductSection";
import Products from "@/app/layout/Products";
import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { Slug } from "@/app/types/types";
import { ProductPage } from "@/app/types/types";
import { getData } from "@/app/utils/getData";
import generateSlugs from "@/app/utils/generateSlugs";

export const preferredRegion = ["fra1"];
export const dynamic = "force-dynamic";

export async function generateStaticParams() {
  const params = await fetch(`${process.env.API_URL}/api/auctions`).then(
    (res) => res.json()
  );

  const slugs = generateSlugs(params);

  return slugs.map((slug: Slug) => ({
    slug: slug.slug,
  }));
}

export async function generateMetadata(
  { params }: { params: Slug },
  parent: ResolvingMetadata
): Promise<Metadata> {
  console.log(params);

  const product = await getData(params);
  const url = "https://noanzo.pl";
  return {
    title: `${product[0]?.title} - noanzo.pl`,
    description: product[0]?.description,
    robots: "index, follow",
    alternates: {
      canonical: `${url}/produkt/${params.slug}`,
    },
    openGraph: {
      title: `${product[0]?.title} - noanzo.pl`,
      description: product[0]?.description,
      locale: "pl",
      images: [
        {
          url: (() => {
            const link = product[0]?.image.filter(
              (item: any) => item.thumbnail === true
            );
            if (!product[0]) {
              notFound();
            }
            if (link[0]?.url) {
              return link[0].url;
            } else {
              return product[0].image[0].url;
            }
          })(),
          alt: product[0]?.title,
        },
      ],
    },
  };
}

export default async function Page({ params }: { params: Slug }) {
  const data = await getData(params);
  if (!data || data[0] === null) {
    notFound();
  }
  const product: ProductPage = {
    title: data[0].title,
    description: data[0].description,
    price: data[0].price,
    image: data[0].image,
    imageLarge: data[0].imageLarge,
  };

  return (
    <main>
      <Navbar />
      <div className='container mx-auto sm:w-4/5 lg:w-11/12 xl:sm:w-4/5 p-2'>
        <ProductSection>
          <Gallery product={product} />
          <ProductDescription product={product} />
        </ProductSection>
      </div>
      <Products />
    </main>
  );
}

When i try something like this:

export async function generateStaticParams() {
  const params = await fetch(`${process.env.API_URL}/api/auctions`).then(
    (res) => res.json()
  );

  return params.map((slug: Slug) => ({
    slug: slug.slug,
  }));
}

Above code works and returns id’s of each item returned from api as slug. How does it “decide” to choose “id” instead of eg. “title” which is also in my data:

Here’s link to my data: api link

How to capture audio realtime in browser?

I’m interested in capturing audio from Google Meet calls and performing real-time transcription using an API within my browser extension app. While I’m aware of WebRTC as a potential solution, I’m still don’t understand how to implement it. Could someone provide guidance on how to utilize WebRTC for this purpose or something similar.

Please, bear with me and thanks in advance!!

Javascript base64 image url replaces all “” for spaces?

I am loosing my mind! Why is the browser stripping all of the in my base64 data?

I log the data and it has them before I put the url into the element but, then it looks like this (with spaces instead of ‘s)

enter image description here

        $('#content').append(`
          <div id="pool_${cc}" class="pool" style="position:relative;top:0px;left:0px;width:100%;right:0px;margin-top:${n == 0 ? '15' : '25'}px;">
            <div class="black win" style="position:relative;top:0px;left:0px;width:100%;right:0px;height:100px;background:#000000a6;">
              <div class="coin" id="cc_${cc}" style="position:absolute;top:25px;left:-25px;width:50px;height:50px;background-image:url(${r.cc[cc]});background-repeat:no-repeat;background-size:50px auto;background-position:center;"></div>
              <div style="position:absolute;top:8px;left:40px;line-height:28px;width:calc(100% - 155px);">
                <b>
                  ${(cc == r.coin ? `<b style="color:#00a2e3;font-family:black;font-style:italic;margin-right:4px;"><i class="fas fa-caret-right" style="font-style:italic;"></i><i class="fas fa-caret-right" style="font-style:italic;"></i> ${cc.toUpperCase()}</b>` : cc.toUpperCase())}
                </b>
                <div style="font-size:10px;">
                  <div style="display:inline-block;margin-right:10px;"><span style="opacity:0.5;">version:</span> 0.0.1</div> 
                  <div style="display:inline-block;margin-right:10px;"><span style="opacity:0.5;">Date:</span> Thu Mar 07 2024 15:11:48</div>
                  <div style="display:inline-block;margin-right:10px;"><span style="opacity:0.5;">Proven:</span> ${!undetermined}</div>
                </div>
              </div>
              <div class="switchCoin btn1" style="color:#cccccc;background:#00000038;right:15px;">SWITCH</div>
              ${undetermined && `<div class="deleteCoin btn1" style="color:#cccccc;background:#00000038;right:65px;">DELETE</div>`}
            </div>
          </div>`
        );

This Works fine: $('#cc_' + cc).css('backgroundImage', 'url(' + r.cc[cc] + ')'); so do the special quotes mess it up?

Programming Basics – JavaScript [closed]

I am trying to solve this task:

Movie Stars

The accountant of the “Star City” cinema center hires you to write a program that calculates the salaries of the actors. Each production has a budget for actors. Until the “ACTION” command is given, you will receive the name of the actor and their salary. If the actor’s name is longer than 15 characters, their salary will be 20% of the remaining budget at that point. If the budget runs out at any point, the program should stop.

Input

First, read one line from the console:

  • Budget for actors – a floating-point number in the range [1000.0… 2 100 000.0]

Then one or two lines are read repeatedly until the command “ACTION” or until the budget runs out:

  • Actor’s name – a string

If the actor name contains less than or equal to 15 characters:

  • Salary – a floating-point number in the range [250.0… 1 000 000.0]

Output

Print one line on the console:

  • If the budget is enough:

    "We are left with {budget left} USD."
    
  • If the budget is NOT enough:

    "We need {budget needed} USD for our actors."
    

The result must be formatted to the second digit after the decimal point!

This is the code I wrote:

function solve(input) {
  let budget = Number(input.shift());
  let totalSalary = 0;

  while (input.length > 0 && input[0] !== "ACTION") {
    let actorName = input.shift();
    let actorSalary = Number(input.shift());

    if (actorName.length > 15) {
      actorSalary = budget * 0.2;
    }

    if (budget >= actorSalary) {
      budget -= actorSalary;
      totalSalary += actorSalary;
    } else {
      let budgetNeeded = actorSalary - budget;
      console.log(`We need ${budgetNeeded.toFixed(2)} USD for our actors.`);
      return;
    }
  }

  console.log(`We are left with ${budget.toFixed(2)} USD.`);
}

It only passes 60/100 tests. What is my mistake?

javascript function changes when used with jakarta ee

I am starting my long and bumpy road to move website from shit i made 20 years ago to Jakarta ee backend, mysql and html javascript frontend. Have some success with java, but problems in javascript.

In my JSP I have javascript function to make thumbnails (chatgpt helped me):

// Generate thumbnails and add click event listeners
                imageData.forEach((data, index) => {
                    const thumbnail = document.createElement('div');
                    thumbnail.classList.add('thumbnail');
                    thumbnail.innerHTML = `<img src="${data.url}" alt="Thumbnail ${index + 1}">`;
                    thumbnail.addEventListener('click', () => displayImage(index));
                    galleryContainer.appendChild(thumbnail);
                });

Localy it works fine, but when it comes back from tomcat fifth line is truncated:

                // Generate thumbnails and add click event listeners
                imageData.forEach((data, index) => {
                    const thumbnail = document.createElement('div');
                    thumbnail.classList.add('thumbnail');
                    thumbnail.innerHTML = `<img src="" alt="Thumbnail 1">`;
                    thumbnail.addEventListener('click', () => displayImage(index));
                    galleryContainer.appendChild(thumbnail);
                });

what could be wrong and how to avoid it?

I expected that jsp content would be the same, only with added image list (which works fine).

JavaScript: Object.keys() as part of a function

I´ve searched for a solution all afternoon. First I was enthusiastic but now I´m just annoid.
Maybe you can help me. Maybe there is no solution.

If you want to get the “name” of a variable you simply can use Object.keys().

const myFirstName = 'John';
console.log(myFirstName);
console.log(Object.keys({myFirstName})[0]);

BUT if you want to write a function and use the variable as the parameter,
this solution does not work anymore.

function hfr_log(variable)
{
    let tmp_variable = variable;
    let tmp_s_variable_name = Object.keys({variable})[0];
    let tmp_variable_content = variable;

    console.log(`tmp_variable = '${tmp_variable}'`);
    console.log(`tmp_s_variable_name = '${tmp_s_variable_name}'`);
    console.log(`tmp_variable_content = ${tmp_variable_content}`);
}

I’ve tried several approaches on how to pass the variable, but I’m running out of ideas.
Is it even possible?

Sorry for the beginner question, but I’m afraid I’m a beginner. :/

In any case, thank you very much for your time and your suggestions! 🙂