Categories
discuss

How to load custom script in react?

This is somewhat similar to this question:

Adding script tag to React/JSX

But in my case I am loading a script like this:

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','ID');</script>
<!-- End Google Tag Manager -->

Now I know there is a npm package for the google tag manager but I am curious if I would like to do this in a custom way how would I go about?

In the above question I see a lot of:

const script = document.createElement("script");

script.src = "https://use.typekit.net/foobar.js";
script.async = true;

document.body.appendChild(script);

Which is fine but if I have a function inside of the loaded script how would I go about executing this correctly?

Answer

To add a random script like this, you could:

  1. Add the script to your index.html
  2. Paste the code to a file and use an import statement.
  3. Dynamically load the script once the user does something, using code splitting.

1. Adding the script to your HTML

Just stick the script tags in your index.html file, preferably at the end of the body tags. If using create-react-app, the index.html file is located in the public directory:

<body>
  <div id="root"></div>
  <script>/* your script here */</script>
</body>

2. Import from file

Alternatively, you could paste the script into a .js file, and import it from anywhere in your code. A good place to import general scripts would be in your index.js entry point file. This approach has the benefit of including the script with the rest of your js bundle, enabling minification and tree shaking.

// index.js
import "../path/to/your/script-file";

3. Code splitting Lastly, if you would like to dynamically load a piece of js code in a certain point in time, while making sure it isn’t part of your starting bundle, you could do code splitting, using dynamic imports. https://create-react-app.dev/docs/code-splitting

function App() {
  function handleLoadScript() {
    import('./your-script')
      .then(({ functionFromModule }) => {
        // Use functionFromModule 
      })
      .catch(err => {
        // Handle failure
      });
  };

  return <button onClick={handleLoadScript}>Load</button>;
}
Categories
discuss

How to round off to the closest hour if its only 5 minutes ahead or behind?

I want to round off an Instant to its closest hour in Java, but only if it’s within 5 minutes of the closest hour.

Suppose the time is: 2021-02-08T19:02:49.594
Expected result: 2021-02-08T19:00:00.000

Similarly, if the time is: 2021-02-08T19:56:49.594
Expected result: 2021-02-08T20:00:00.000

But if the time is 2021-02-08T19:54:49.594 or 2021-02-08T19:06:49.594 then do nothing.

Answer

You can simply check the minute part of the date-time and truncate it to hours as per the requirement.

Demo:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

class Main {
    public static void main(String[] args) {
        // Test
        String[] arr = { "2021-02-08T19:02:49.594", "2021-02-08T19:56:49.594", "2021-02-08T19:54:49.594",
                "2021-02-08T19:06:49.594" };

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");

        for (String s : arr) {
            System.out.println(roundToNearestHour(s).format(dtf));
        }
    }

    static LocalDateTime roundToNearestHour(String str) {
        LocalDateTime ldt = LocalDateTime.parse(str);
        int minute = ldt.getMinute();
        return minute < 5 ? ldt.truncatedTo(ChronoUnit.HOURS)
                : (minute >= 55 ? ldt.plusHours(1).truncatedTo(ChronoUnit.HOURS) : ldt);
    }
}

Output:

2021-02-08T19:00:00.000
2021-02-08T20:00:00.000
2021-02-08T19:54:49.594
2021-02-08T19:06:49.594
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..