How to fetch multiple google fonts - html

I'm working on a personal project in NextJS which uses around 5 Google fonts.
The fonts are being fetched only if the page New is reloaded or if I navigate to the page using <a></a> tag instead of <Link></Link>.
This is my current code for the page that requires the fonts,
export async function getStaticProps() {
const fonts = getFontNames(); // returns a static list of strings like ['Monserrat', 'Product Sans', ...].
const fontsLink = "https://fonts.googleapis.com/css2?family=" + fonts.map(cV => cV.replace(/ /g, '+')).join('&family=') + "&display=swap"
return {
props: {
fonts,
fontsLink
}
}
}
export default function New({ fonts, fontsLink }) {
return (
<div className={styles.container}>
<Head>
<title>New</title>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link href={fontsLink} rel="stylesheet" />
</Head>
...
</div>
}
This is how I navigate to the page New ,
<Link href="/new">
<a className={styles.card}>
<h2>New →</h2>
</a>
</Link>

Make sure you've disabled browser cache in the network tab before testing fonts.
import PageLayout from "../components/Page/PageLayout"
import Head from "next/head"
export default function About({ fonts, fontsLink }) {
return (
<Head>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link href={fontsLink} rel="stylesheet" />
</Head>
)
}
export async function getStaticProps() {
const fonts = ["Monserrat", "Product Sans", "Girassol"]
const fontsLink =
"https://fonts.googleapis.com/css2?family=" +
fonts.map((cV) => cV.replace(/ /g, "+")).join("&family=") +
"&display=swap"
return {
props: {
fonts,
fontsLink,
},
}
}
Using either means of navigation loads the fonts for me.
<Link href="/About">About</Link>
<Link href="/About">
<a>
<h2>About page using Link</h2>
</a>
</Link>

Related

React route adds margin to the page

This doesn't seem to make any sense, but I'll explain and add code.
Yesterday while working on my app I suddenly realized that there are unnecessary margins on the borders of the page. The type that would appear if you didn't reset the margin and padding.
I've tried eliminating things at the source, and noticed that I only get those margins once I add a route (doesn't matter which one). When there is no route, no margins.
I've tried checking one of the pages (maybe I've made some mistake in all of them) and after seeing no issue, I've decided to create a test page which is completely empty. If I add the route to that page, the margins appear. If I don't, they don't.
What could be the reason?
Attaching code below.
index.tsx
import React from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store/store";
import { App } from "./App";
import "./styles.css";
const container = document.getElementById("root")!;
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
styles.css
* {
margin: 0px;
padding: 0px;
font-family: Cabin;
}
App.tsx
import { Route } from "react-router-dom";
import Wrapper from "./wrapper";
import {
TestPage,
} from "./pages";
export function App() {
return (
<Wrapper data-test="app">
<Route path="/" element={<TestPage />} />
</Wrapper>
);
}
TestPage (it is import and rexported from an index.ts file, and again from the main "pages" index file. Those files are simply re-exporting the component below.
import { Box } from "rebass";
import { TestPresentational } from "../presentational";
export const TestContainer = () => {
return <Box>Hola</Box>;
};
Just in case, this is my public index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cabin:wght#400;500;600;700&family=Open+Sans:wght#300;400;500;600;700;800&display=swap" rel="stylesheet">
<title>Travel buddy</title>
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
EDIT:
It's been asked if it is possible the the Box component added the margins.
I've tried returning this from App.tsx instead of the wrapper component, and had no issues.
return (
<Box
sx={{
width: "100vw",
height: "100vh",
backgroundColor: "blue",
margin: "0px",
padding: "0px",
}}
></Box>
);
So no, the component is not the issue. An interesting thing that campe up though, is if I've returned that without commenting out the wrapper return (but making its code unreachable) I got the margins again.
I had a new library that imported a css file that added padding to page. Found it thanks to #Andre suggestion (never got comfortable with the browser inspector but this forced me to, so glad it happened).

How to inject tailwind css into an iframe without using play cdn of tailwind

I'm working with svelte and made a chat widget, for styling I used tailwindcss.
the main problem with the chat widgets are you have to render them in an iframe so that it doesn't disturb the css of its remote site. so I achieved loading it inside iframe but it rendered without tailwind styles.
// main.ts is my file where I declared the iframe
import './app.css';
import App from './App.svelte';
// you can ignore this interface if you find it confusing
interface IWidget {
iframeContainer: HTMLElement | null;
init: (props: any) => void;
createContainer: () => void;
handleMessage: (event: MessageEvent) => void;
setupListeners: () => void;
}
const app = (() => {
// new App({
// target: document.getElementById('app'),
// });
const iframeContainer = document.createElement('div');
iframeContainer.id = 'my-chat-widget';
document.body.appendChild(iframeContainer);
// create iframe
const iframe = document.createElement('iframe');
iframe.id = 'my-chat-iframe';
iframe.srcdoc = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Support</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght#100;300;400;500;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="my-widget"></div>
</body>
</html>`;
document.getElementById('my-chat-widget').appendChild(iframe);
const iframeWindow: HTMLIFrameElement =
document.getElementById('my-chat-iframe');
document.getElementById('my-chat-iframe').onload = () => {
new App({
target: iframeWindow.contentWindow.document.getElementById('my-widget'),
});
};
})();
export default app;
the file above is similar to index.tsx in react
Basically I'm directly targeting my svelte app into the iframe, only the problem I'am facing is the tailwind css is not loading.
methods I tried
adding Play CDN link from tailwind into head of above file.
(this worked but not feasible as production build)
directly linking the app.css into head of above file.
(this also worked but only in dev mode because the bundler adds its content hash, I want it to be production ready)

Service Workers don't doesn't load pages.html

When I change the pages without loading them in the cache with service workers there are no problems when I go to save the pages in the cache they are no longer found both online and offline. The problem occurs only with pages and not with other elements such as .jpg .png .js .css and some .html elements
When i go to another page after i saved it in the cache
Unable to reach site The web page at link of the page may be temporarily unavailable or has been permanently moved to a new web address.
ERR_FAILED
Service Workers
const staticChacheName = 'site-static'
const assets = [
'/',
'/index.html',
'/Html/Elements/footer.html',
'/Html/Elements/mobile_menu.html',
'/Html/Elements/navbar.html',
'/Html/Pages/film.html', //not working
'/Html/Pages/anime.html', //not working
'/Html/Pages/sitobello.html', //not working
'/Html/Pages/song.html', //not working
'/Html/Pages/amici_home.html', //not working
'/Html/Pages/Amici/tilde.html', //not working
'/Html/Pages/Amici/kloe.html', //not working
'Css/Index/style.css',
'Css/Sito Bello/background.css',
'Css/Sito Bello/section.css',
'Css/Sito Bello/settings.css',
'Css/Song/background.css',
'Css/Song/elementi.css',
'Css/Film/background.css',
'Css/Film/elementi.css',
'Css/Anime/background.css',
'Css/Anime/elementi.css',
'Css/Element/footer.css',
'Css/Element/mobile_menu.css',
'Css/Element/navbar.css',
'Css/Element/scrollbar.css',
'Css/Amici/Home/background.css',
'Css/Amici/Home/elementi.css',
'Css/Amici/Kloe/background.css',
'Css/Amici/Tilde/background.css',
'/Images/Logo.png',
'/Images/Index/background.jpg',
'/Javascript/Element/navbar.js',
'/Javascript/Film/add.js',
'/Javascript/Sito Bello/add.js',
'/Javascript/Sito Bello/settings.js',
'/manifest.webmanifest',
'/Javascript/app.js',
]
//install service worker
self.addEventListener('install', evt => {
// console.log('service worker has been installed')
evt.waitUntil(
caches.open(staticChacheName).then(chache => {
console.log('chaching shell assets')
chache.addAll(assets)
}))
})
//activate service worker
self.addEventListener('activate', evt => {
// console.log('service worker has been activated')
})
self.addEventListener('fetch', evt => {
//console.log('fetch event', evt)
evt.respondWith(
caches.match(evt.request).then(chacheRes => {
return chacheRes || fetch(evt.request)
})
)
})
Example of a page that doesn't work
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<link rel="stylesheet" href="/Css/Element/navbar.css">
<link rel="stylesheet" href="/Css/Element/mobile_menu.css">
<link rel="stylesheet" href="/Css/Film/background.css">
<link rel="stylesheet" href="/Css/Film/elementi.css">
<link rel="stylesheet" href="/Css/Element/footer.css">
<link rel="stylesheet" href="/Css/Element/scrollbar.css">
<link rel="manifest" href="/manifest.webmanifest">
<link rel = "icon" href = "/Images/Logo.png" type = "image/x-icon">
<title>Aside - Film</title>
</head>
<body>
<nav></nav>
<div id="mb-menu"></div>
<h1 id="title">Film</h1>
<div id="films">
<!-- aggiunge film -->
</div>
<footer></footer>
<script src="/Javascript/app.js"></script>
<script src="/Javascript/Film/add.js"></script>
<script src="/Javascript/Element/navbar.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(function(){
$("nav").load("/Html/Elements/navbar.html");
$("footer").load("/Html/Elements/footer.html");
$("#mb-menu").load("/Html/Elements/mobile_menu.html");
});
</script>
</body>
</html>
Site structure
what am I doing wrong? because I would like my site to work offline too but not being able to load the other pages it works only in the home

How to load CSS and Bootstrap files into server using node.js?

I have a html file called myfile.html that displays 'Hello World'. My css file called myfile.css is used to insert background image. My bootstrap files are used to insert a image in the form of a circle.
The HTML file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
</head>
<body>
<h1>Hello World!!</h1>
<img src="public\pinky.jpg" class="img-circle">
</body>
</html>
My CSS file is as follows:
body {
background-image: url('fishy.jpg');
}
My node.js file called new.js is as follows:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/',function (req,res) {
console.log(__dirname)
res.sendFile(__dirname+"/myfile.html")
})
app.listen(3000, function() {
console.log('Example app listening on port 3000!')
})
My main folder is called Bootsstrap and it has the following contents:
Bootsstrap
-myfile.html
-public /*Folder*/
/*inside public folder*/
-myfile.css
-css
-js
-fonts
-fishy.jpg /*background image*/
-pinky.jpg /*circular image*/
I open Command Prompt from Bootsstrap folder and run
node new.js
I get the message as:
'Example app listening on port 3000!'
When I open Chrome Browser and type localhost:3000, I get only 'Hello World'.The images are not getting displayed. I get an Error 404.
What can I do in order to run my HTML file in server using node.js by including all my css and bootstrap files?
You must not use the public path in your html. Also, in URLs use always forward slashes. Backslashes are just for Windows directories.
<!DOCTYPE html> <html> <head> <title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
</head> <body> <h1>Hello World!!</h1>
<img src="pinky.jpg" class="img-circle"> </body> </html>
replace
<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
by
<link rel="stylesheet" type="text/css" href="css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
If you want to serve static files, such as html files, css, images, you need to make them available for the public. In your existing setup, only myfile.html is available for the public. Since you use css and other files from your server, you need to make them available also. The best way to achieve is to create a public folder and let express to make all the files available in the public folder.
Add to node.js
app.use('/', express.static('public'));
and rename your myfile.html to index.html
and in your index.html file
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
For example, your node.js should look like something
const express = require('express');
const app = express();
app.use('/', express.static('public'));
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
For more info Serving static files in Express
Edit
Your folder structure should be. no need of bootstap folder
public //public folder
-index.html
-myfile.css
-css
-js
-fonts
-fishy.jpg
-pinky.jpg

How to get IE 11 not support FormData in ReactJS. FormData.get() not supported

The code works fine on FF and Chrome but will not run on IE.
I read that I need to add another meta tag to the index.html but this did not solve the issue. Does IE not support FormData? I can update the state to store the name directly in the dropHandler method but want to know why FormData does not work for IE.
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Error:
SCRIPT438: Object doesn't support property or method 'get'
Code that causes error:
this.state.jsonFile.get('name')
React Component:
'use strict';
const React = require('react');
const ReactDOM = require('react-dom');
class TestCaseDialog extends React.Component {
constructor(props) {
super(props);
this.state = {jsonFile: null, loadingPage: false, loadingMessage: '', errorAlertVisible: false, errorAlertMessage: '', filePath: null};
this.dropHandler = this.dropHandler.bind(this);
}
dropHandler(file) {
var jsonFile = new FormData();
jsonFile.append('file', file[0]);
jsonFile.append('name', file[0].name);
.....
this.setState({jsonFile: jsonFile,
filePath: resp.text});
}
render() {
...
dropZone.push = <div key='file-details'>File has been uploaded: {this.state.jsonFile.get('name')}</div>;
...
return (
<div>
{this.state.loadingPage ? <LoadingPage key='loadingPage' loadingMessage={this.state.loadingMessage} /> : (
<div key="dz">
{dropZone}
</div>
)}
{errorAlert}
</div>
);
}
}
module.exports = TestCaseDialog
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- cerulean style -->
<!--link rel="stylesheet" href="https://bootswatch.com/cerulean/bootstrap.css" /-->
<!--link rel="stylesheet" href="https://bootswatch.com/cerulean/bootstrap-theme.min.css" /-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" />
<link rel="stylesheet" href="/main.css" />
</head>
<body>
<!--div>
<Logged in as: <span th:text="${#authentication.name}">user</span>.
<form th:action="#{/logout}" method="post">
<input type="submit" value="Log Out"/>
</form>
</div-->
<div id="react"></div>
<script src="built/bundle.js"></script>
</body>
</html>