Skip to content

Instantly share code, notes, and snippets.

View jpvincent's full-sized avatar

Jean-Pierre Vincent jpvincent

View GitHub Profile
@jpvincent
jpvincent / lazy_modal_react.jsx
Created October 24, 2023 09:02
lazy load react component
import { lazy, useState, useTransition } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
const Modal = lazy(() => import('./Modal.jsx'));
export default function App() {
const [isPending, startTransition] = useTransition();
const [opened, setOpened] = useState(false);
function openModal() {
@jpvincent
jpvincent / lazy_modal_svelte.jsx
Created October 24, 2023 09:01
Lazy loading svelte component
<script>
let lazyModalComponent;
let isPending = false;
function openModal() {
isPending = true;
lazyModalComponent = import(`./Modal.svelte`);
lazyModalComponent.catch((error) => {
// gestion en cas d'erreur de connexion ici
}).finally(() => {
const timings = performance.getEntriesByType('navigation')[0]
const allEntries = performance.getEntries()
const customMetrics = allEntries
.filter(entry => ['mark', 'measure'].includes(entry.entryType )) // array of PerformanceMark / PerformanceMeasure objects
.reduce((final, current) => { // make an object
final[current.entryType.toUpperCase() + ' — ' + current.name] // key name : "MARK — loadInAsync que/query_grid_webpart start"
= Math.round(
current.entryType === 'measure' ? current.duration : current.startTime
)
// idée originale : https://developers.google.com/web/fundamentals/performance/user-centric-performance-metrics#load_abandonment
window.__trackAbandons = () => {
// Remove the listener so it only runs once.
document.removeEventListener('visibilitychange', window.__trackAbandons);
const ANALYTICS_URL = 'https://www.google-analytics.com/collect';
const GA_COOKIE = document.cookie.replace(
/(?:(?:^|.*;)\s*_ga\s*\=\s*(?:\w+\.\d\.)([^;]*).*$)|^.*$/, '$1');
const TRACKING_ID = 'UA-XXXXX-Y';
const CLIENT_ID = GA_COOKIE || (Math.random() * Math.pow(2, 52));
@jpvincent
jpvincent / proposition syntaxe Jest — webdriver.js
Created December 29, 2017 14:54
Jest marche bien avec Webdriver, mais la syntaxe peut être lourde. On pourrait étendre l'assert de Jest pour intégrer les appels webdriver
// actuellement
expect(await browser.isSelected('[name=CustomClearanceRadios]'))
.toBe(true)
// proposition
expect.el('[name=CustomClearanceRadios]')
.toBeSelected()
// actuellement
expect(await browser.getValue('#ShipperEmail'))
.toBe('jp@made.this')
@jpvincent
jpvincent / inclusion-asynchrone.js
Created October 28, 2016 18:18
inclusion asynchrone de JS prenant en compte IE < 10 et ne ralentissant pas le body.onload
// Pour rappel, voici la manière de faire de GA
/*(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
*/
// C'est compatible partout et asynchrone, mais dans le cas de IE < 10, si le script est déclenché trop tôt, il ralentit window.onload
// Il faut donc juste écouter window.onload et déclencher ce script en asynchrone, quitte à le ralentir
function includeGa(){
@jpvincent
jpvincent / multiple-spof-check.js
Created October 28, 2016 15:23
Compile and sort multiple runs of spofcheck. Display scores in CLI
// Warning : the original spofcheck works with an old version of Node. 0.10.36 did it for me.
// npm install spofcheck before
// For CLI display only : the original spofcheck could also generate a junit.xml file to be used in continuous integration
const spofcheck = require('spofcheck')
const url = require('url')
const Table = require('cli-table')
const URLs = [
'http://www.vanityfair.fr/',
// 'http://www.vanityfair.fr/video',
var namespace = window;
// Font Loader
namespace.loadFont = function(familyName, fileName, callback) {
var pathToFonts = 'Content/fonts/';
function applyFont() {
var css = '@font-face { font-family: "' + familyName + '";\
src: url("'+pathToFonts+ fileName + '.eot");\
src: url("'+pathToFonts+ fileName + '.eot?#iefix") format("embedded-opentype"),\
url("'+pathToFonts+ fileName + '.woff2") format("woff2"),\
@jpvincent
jpvincent / optimizedFor.js
Last active November 25, 2021 17:12
never blocking loop mechanism, using setTimeout 0 trick and time control to break the loop and let the browser breath
/**
* NEVER BLOCKING LOOP : implementation of the infamous setTimeout 0 hack, with time checking in order to guarantee fluidity without sacrificing execution speed.
*
* USAGE :
* var array = ["a way too big array that is heavy to process"]
* optimizeFor({
* nbIterations: array.length,
* each:function( index ) {
* doSomethingUsefulWith( array[ index ] );
* },
{
"eqeqeq": true, // This options prohibits the use of == and != in favor of === and !==.
"noarg": true, // This option prohibits the use of arguments.caller and arguments.callee
"undef": true, // This option prohibits the use of explicitly undeclared variables
"unused": true, // This option warns when you define and never use your variables
"trailing": true, // This option makes it an error to leave a trailing whitespace in your code
"maxdepth": 3,
"camelCase": true,
"curly": true, // This option requires you to always put curly braces around blocks in loops and conditionals
"immed": true, // This option prohibits the use of immediate function invocations without wrapping them in parentheses