How to preload a script in nextjs? - javascript

I am trying to add a script in my website.
The problem is the script doesn't load the first time the page renders after a couple of refreshes it works and the iFrame it's responsible for shows up.
I tried a few different ways but nothing worked
Here is the code:
_app.js
<Script
src="https://boards.greenhouse.io/embed"
onError={(e) => {
console.error('Script failed to load', e)
}}
/>
Notice that onError doesn't show any error either.
I also tried loading it in the component itself like but still doesn't work
useEffect(() => {
console.log("lets go");
<Script src="https://boards.greenhouse.io/embed" />
}, []);
I gave it the strategy attribute and tried all the values it can have but that didn't work either.

The page I was loading the script on was being navigated using
<Link href=""></Link>
I had to replace it with
and it worked, hope it helps.

Related

React, loading a script inside a form (mercadopago)

I am trying to implement some payment system (MercadoPago).
According to the doc, it's just pasting this:
<form method="POST">
<script
src="https://www.mercadopago.com.pe/integrations/v1/web-payment-checkout.js"
data-preference-id="589788715-2e52aeec-8275-487c-88ee-1a08cff37c08"
></script>
</form>
Pasting it in a pure html file works fine: a button appears and clicking it opens a modal to pay with a credit card as expected. However this doesn't work in React since it's dynamically loading a script. Hence, I tried using an effect hook to insert the <script> on load as such:
const App = () => {
const setMercadoPagoPreferences = async () => {
const script = document.createElement('script');
script.src =
'https://www.mercadopago.com.ar/integrations/v1/web-payment-checkout.js';
script.async = true; // commenting or uncommenting seems to have no effect
script.setAttribute(
'data-preference-id',
'589788715-2e52aeec-8275-487c-88ee-1a08cff37c08'
);
document.getElementById('mercadoForm').appendChild(script);
};
useEffect(() => {
setMercadoPagoPreferences();
}, []);
return <form action='/procesar-pago' method='POST' id='mercadoForm' />;
};
This loads correctly the script, it seems, as a button to pay is appended to the page. Clicking it however opens a modal that says "oh no, something bad happened". This doesn't happen on my .html example above; so it must be because of how React is loading the script or something like that. It doesn't work on either the dev or the production build.
Edit: As suggested, I tried using refs instead of directly appending childs but this did not seem to have any impact, it still won't work.
I dont know this framework but maybe thats the way: It looks like this guy has similar problem right here.
I think there is problem because script does not load on time. So maybe lets try this:
script.onload = () => {
document.getElementById('mercadoForm').appendChild(script);
};
In addtion there is build in mechanism in react ref like HERE instead of document.getElementById
Your technique would've work if it weren't for mercadolibre.
Apparently, the use of the page you are trying to load is not allowed by mercadolibre. It's like you're trying to load mercadolibre inside an Iframe which they probably blocked using CSP header. Specifically they are setting the Content-Security-Policy tag to frame-ancestors 'self'. It's a security restriction standard that does not allow the use of pages from that domain within elements Iframe.

alt text for script tag in html body

I embed a GitHub gist on my webpage using the script tag as follows
<script src="https://gist.github.com/uname/id.js"></script>
Is there a way to provide alt text in case the gist doesn't load? I tried the alt attribute within the script tag but that doesn't seem to work.
Looking at how gist's are embedded they use document.write.
And then inside there it will create some markup, so what we could do is check to see if the markup has been created after waiting a while, if no gist has been loaded then they won't be any markup with a class of .gist.
Below is a working example.
if you run the snippet it should fail after 5 seconds and show a message, if you then replace 4577639.js_bad with just 4577639.js it will then hopefully work and failed to load message should not appear.
ps. Not sure if this is the official way of falling back, but it seems to work ok.
setTimeout(function () {
if (!document.querySelector(".gist")) {
document.querySelector("#failed-to-load").
style.display = "block";
}
}, 5000);
<div id="failed-to-load" style="display:none">
Failed to load Gist
</div>
<script src="https://gist.github.com/claudemamo/4577639.js_bad"></script>

add class to a component in jsf template

I'm using a template for my website but I want to add a class to <li> element when clicking it , I can do it already as i saw the result in the debug mood but when i moved to this page the class="active" which i added is removed again.
Here is my img in debug mood and the script which i use.
So how can I save the added class to this element?
<script>
$(document).ready(function () {
$("#liEmpCreate").click(function () {
console.log("rerererererer ay2 ay2 ay2 ");
$("#liEmpCreate").addClass("active");
});
});
</script>
result in debug mood before redirect to this page
Finally I found the answer :) .
As I mentioned above in the question , i wanted to add this class to an element of sidebar which refers to the pages i opened. So i have all these elements in all pages, then i put an id foreach tag and tried to use the same script in each page separately , but unfortunately it doesn't work either.
So i tried to put my script everywhere in my page but when i put it after my form and before </ui:define> i found the console.log appears in the browser console, but it doesn't work as i wished because of this code is called and then the page is rendered again. finally i used the below code and it worked correctly.
<script>
$(window).on('load', function() {
$("#liEmpCreate").addClass("active");
});
</script>
<h:outputStylesheet library="js2" name="jquery-3.2.1.min.js"/>
</ui:define>

Link + on(pagecontainershow) fail

I have a simple app done with jQuery Mobile, in some point I have this:
Start!
which loads a new HTML with a lot of jquery mobile pages:
<div data-role="page">
I have defined, in my external JS file, an global variable:
var startTimeQuestion;
And this method, which is inside my HTML (test_es.html):
<script>
$(document).on('pagecontainershow', function() {
console.log("Storing time..");
startTimeQuestion = new Date().getTime();
});
</script>
The problem is that when I click on the button it loads correctly the file but it seems like it don't load the JS or the function or I don't know, because when I'm going to use my startTimeQuestion variable it says UNDEFINED and it don't show in the console the 'Storing time..'. If a reload the page, it works fine.
I have tried to do an '$.(document).ready()' function for the first time I load the page but still not working. It looks like test_es.html it isn't loading my custom.css and my test.js file until I reload completely the page. So I supposed that the error is in how I call my test_es.html, it isn't this:
Start!
the correct way to do it?
Thanks.
Thanks to the comment before I found the solution, it was as simple as put the 'data-ajax' attribute to false this way:
Start!

Galleria theme occasionally not loading

I am using the Galleria slideshow on my site, but I've noticed an error that seems to happen very randomly. Most of the time the slideshow loads correctrly but once in a while I get this error:
Uncaught Error: Fatal error: Theme at javascript/themes/classic/galleria.classic.js
could not load, check theme path.
When I reload the page, it's all back to normal.
This is the code I'm using to load it:
<script>
// Load the classic theme
Galleria.loadTheme('javascript/themes/classic/galleria.classic.js');
</script>
I have searched around but still haven't found a solution that works. My personal idea was to have a script that keeps loading until it succeeds, since on reload the page works.
How would I do this?
1 Try the latest build at gihub: https://github.com/aino/galleria/blob/master/src/galleria.js
2 Try loading the theme using a script tag instead:
<script src="javascript/themes/classic/galleria.classic.js"></script>
I adopted the method pointed out by David, loading the theme using a script tag:
<script src="javascript/themes/classic/galleria.classic.js"></script>
But was eventually getting another error (Fatal error: Theme CSS could not load after 20 sec). I'd also recommend adding the CSS using a link tag:
<link rel="stylesheet" type="text/css" href="galleria/themes/classic/galleria.classic.css" />
I had a similar message today when I tried using Galleria. It happened only in Firefox. What I did to get around it is to add the theme stylesheet link directly in the head. I kept the theme script link in too, after the stylesheet, just in case it was needed. After that, the error message went away and Galleria is working as it should.
Judging from where the error message comes from, and considering the random occurrences, this issue could be from simply hitting the timeout when loading:
Galleria.loadTheme = function( src, options ) {
var loaded = false,
length = _galleries.length,
err = window.setTimeout( function() {
Galleria.raise( "Theme at " + src + " could not load, check theme path.", true );
}, 5000 );
In version 1.2.2, the timeout is just 2 seconds, in the above (1.2.6) the timeout is 5 seconds. So upgrading to the later version, or customizing the timeout is definitely something to try.
Given the random behavior, it feels like a browser bug. More specifically, that the browser looses track of the base URL. I would give the full path from the webroot and see if the error goes away. For example:
Galleria.loadTheme('/gallery/javascript/themes/classic/galleria.classic.js');
If this don't help, try:
try {
Galleria.loadTheme('javascript/themes/classic/galleria.classic.js');
}
catch(e) {
location.reload();
}
But this can go infinitely. I would try to get to the bottom of the error and start with different browsers to rule out a bug in your code.
The Beginners Guide states that the script tag in which you load the theme needs to be after the images in the html source. You have probably added the script tag in the head tag. Example from the guide:
<body>
<div id="galleria">
<img src="photo1.jpg">
<img src="photo2.jpg">
<img src="photo3.jpg">
</div>
<script>
Galleria.loadTheme('galleria/themes/classic/galleria.classic.min.js');
Galleria.run('#galleria');
</script>
</body>

Categories