Web Performance Calendar » Native Image Lazy Loading in Chro...
Strategy

Web Performance Calendar » Native Image Lazy Loading in Chro…


I recently redesigned my personal site and the first version was very lean. As I started adding content to pages and writing new blog posts, it made sense to implement image lazy-loading to improve performance.

There are many JS-based solutions for image lazy-loading but I did not want to invest time in finding the best one. So, I quickly decided to go for native lazy-loading.

Browser support for native lazy-loading is currently limited but support in Opera and Chrome is good enough for me.

Implementing native lazy-loading is easy: simply add loading="lazy" to img elements. Awesome!

I commited the change, deployed my Eleventy-powered site to Netlify and then tested how images load in Chrome. I was disappointed.

Chrome fetches all the images on my homepage on page load, while none of the images are above the fold on mobile and only some on desktop.

What is Chrome’s native image lazy-loading logic?

When does Chrome decide to fetch a below-the-fold loading="lazy" image?
Being disappointed with what I saw on my own site, I set out to find the answer to this question, like so:

  • find a very long blog post that has loading="lazy" images at the bottom: An In-Depth Tutorial of Webmentions + Eleventy
  • load the page in Chrome, then clear the Network panel
  • scroll down, a few hundred pixels at a time until those lazy-loaded images are fetched
  • in console, get the value of window.pageYOffset
  • scroll down until the top of the lazy-loaded images become visible

I see the lazy-loaded images being fetched at ~ window.pageYOffset = 8500 on desktop and they become visible at ~ window.pageYOffset = 11500. So, the image lazy-load logic of Chrome seems to be: if the image is 3000 or less pixels below the viewport, load it.

3000 pixels… that is a lot!

Load-in distance threshold

It’s always good to compare test results against the spec or official documentation.

I read the native lazy-loading explainer article on web.dev. The section Load-in distance threshold states:

All images and iframes that are above the fold—that is, immediately viewable without scrolling—load normally. Those that are far below the device viewport are only fetched when the user scrolls near them.

That section in the article also mentions the “distance threshold is not fixed and varies depending on several factors”. These factors include the type of resource being fetched (image or iframe), whether Lite mode is enabled on Chrome for Android and the effective connection type.

Thankfully, there is also a link to the relevant code in Chromium source: Lazy image loading distance-from-viewport thresholds for different effective connection types.

The code is easy to read and confirms my findings: if the effective connection type is 4g, Chrome will fetch images with loading="lazy" when they are within 3000 pixels of the current scroll position.

A Better Lazy-Loading Logic

On my 13 inch macbook, with Dock positioned on the left, the viewport height in Chrome is 786 pixels so images with loading="lazy" that are more than 4x the viewport down the page are eagerly fetched by Chrome on page load.

In my opinion, that is waaaaay too eager. Why not use a lower threshold value like 1000 pixels? Or even better: base the threshold value on the actual viewport height.

I will file a bug with Chromium soon and see where that leads.

If I would need to implement image lazy-loading on a high-traffic e-commerce site today, I’d very likely go for a JS-based solution. Partly because the native solution only works in Chrome, but also because Chrome’s implementation is too eager and therefore not so effective.



Source link

installing necessary dependencies
Strategy

Navigation in a React Native Web Application


“React Native for Web” makes it possible to run React Native components and APIs on the web using React DOM.

Setting up navigation in 
react–native–web
 is challenging as the navigation system works quite differently in
 apps vs
 browser. In this article, we’ll set up the most popular react-navigation on to react-native-web.

Using React Navigation in React Native Web

React navigation is the most famous library for navigation in reactnative. In this section, we’ll try to integrate react-navigation in reactnativeweb.

Prerequisite

For this setup, we’ll be using expo as the platform on which we’ll be building our React Native app, which will run on Android, iOS, and the web. Make sure you have expo-cli installed already.

To set up your codebase using expo, check this GitHub link [master branch]. Simply clone the branch and run expo start.

If you are looking for a quick code, then you can check this GitHub link (note: the branch is reactnavigationsetup and not master).

You may also like:
A Look at React Native and React.js.

Installation

Run
 the following command to install 
react
navigation along with other necessary packages, including
react-navigation-stack.

Check your package.json files to ensure all of the above packages are installed. Make sure reactnavigation is version 4+. If you are wondering, “why did we use expo instead of NPM/yarn while installing react–navigation,” then the reason is that expo would look for the correct version of the react–navigation libraries that’d work with the expo version that’s installed in your project.

If you look into the printed console, it uses NPM underneath.

installing necessary dependencies

Installing necessary dependencies

Create a Few Screens

Now, let’s set up a few screens to test our navigation flow:

The above is the code for FeedScreen, which is simple text and a button. The button when clicked should go directly to the profile screen.

The Profile screen is the same as the Feed screen. Both the screens have a button which takes to the other screen.

Let’s also create stack navigation to connect these two screens together:

Since the object that’s passed to CreateStackNavigator Profile comes first, the Profile screen is the default screen of this stack navigator.

Now, in the App.js file, simply render the Home Navigation.

Just run the app using command, expo start, and it should launch the expo bundler for you.

If you press i to launch the Expo app in the iOS simulator in the terminal, the following screen comes up on the display, assuming everything goes well.

Profile screen demo

Profile screen demo

When you click on the Go to Feed button, it should take you to the feed screen.

To run the same setup on to the web, simply press w in your terminal. It will launch the web app in your default browser.

application running in web

Application running in web

The click functionality also works on the web as well. The top border is for the screen title, you can add it by adding navigationOptions to the feed and profile screen like this:

But, there is one problem with the web navigation, the URL doesn’t change when you go from the profile to the feed screen. In the web navigation, it is extremely important to have the change in page reflecting in the URL as well.

In the app, there is no way a user can directly jump to a screen other than the default screen, but in the browser, it is possible; a user can enter a URL.

The good part of react–navigation is that it supports URL updates when the screen changes. The way navigationOptions is added inside the screen class, you can also add a title.

For the profile screen, you can keep the path as empty static path = "".

When you go to http://localhost:19006/feed, the web app would understand that you want to go to the feed screen and will render that for you. Try going to http://localhost:19006/feed directly, and it should render the feed page for you. But when you click on the 
Go to Feed 
button, the URL won’t change.

There are a few other things that we need to do to make this work:
@react-navigation/web also provides a Link module that gets converted into an a tag on to the web.

This module doesn’t work when you try to run the app. So, we use Platform module provided by react–native to differentiate between web and app.

Here, we are conditionally rendering the Link and the Button.

You need to do similar changes for the Profile screen as well. Also, in the navigation container, instead of createAppContainer, you need to use createBrowserApp for the web.

Here is the code for the navigation:

Try running the app in the browser. The Go to feed button click should change the URL to http://localhost:19006/feed.

Also, the app should be running fine on the simulators as well.

Further Reading



Source link

Post image
Strategy

Making Flask app – Is it bad that I can see form data in a P…


Hi all,

I’m new to Flask and I’m working with my team to build a website with a few different business needs. I am trying to figure out how to develop an authentication system in Flask that uses proper standards. Right now I am using Flask, Flask Login and WTF Forms under HTTP. I haven’t implemented HTTPS yet, but I do have an authentication system that hashes on the server side using argon2.

I am wondering – I’m not sure if I’m making my authentication system as secure as possible. As far as I know, I’m not storing clear-text passwords, I’m using a secret key that appends to the session ID (I think, it’s set by env[“SECRET_KEY”] but I don’t do anything with it) and is distributed as a cookie. The cookie contains session information. Right now I do not have CSRF tokens with each form but plan to do so.

I opened the inspector and I can see plain-text information. Even though we’re not serving over HTTPS yet, and there’s no CSRF token (does this change the content of the form anyway?), I’m still wondering if this should ever be visible. I don’t see form data like this for example when I login to Gmail:

Post image

In Chrome DevTools

Is the reason I can see plaintext information in the request because I don’t hash on the client-side first? Should I hash + salt on the client-side and then hash on the server side as well?

Thanks a bunch.



Source link

Installing plugins
Strategy

Vue CLI 3: A Game Changer for Frontend Development


Vue creator Evan You’s recent conference keynote didn’t mention much about new features for Vue, instead focusing almost entirely on Vue CLI 3.

A CLI tool is a mere utility that doesn’t directly add any features to your Vue apps, so why the fuss?

The astonishing rise of Vue’s popularity over the past year has highlighted what developers really care about in a framework: performance, flexibility, and ease of use.

As you’ll see, Vue CLI 3 is a major leap forward in both flexibility and ease of use. It provides your Vue project with instant access to the best build tools from the front-end world, combining them seamlessly with sensible defaults. At the same time, it allows easy configuration and customization to fit your specific needs.

To achieve this, Vue CLI 3 has adopted a new plugin-based architecture, departing from the template-based architecture of versions 1 and 2. Under this new architecture, project configuration is siloed in independent plugins, i.e. one for TypeScript, one for ESLint, etc.

Here are some things you’ll love about Vue CLI 3:

  • No lock-in, as plugins can be added at any point in the development lifecycle.
  • Zero config plugins allow you to spend time developing rather than configuring.
  • Easy to upgrade, as configuration can be customized without “ejecting.”
  • Allows developers to make their own plugins and presets.

Last, but not least, Vue CLI 3 takes you from a blank canvas to a running server really fast allowing you to prototype a project with nothing more than a single .vue file.

You may also like:
Renaming src Folder of a Vue CLI 3 Project.

Plugin Architecture

The base configuration for a Vue CLI 3 project is bare-bones Webpack and Babel. All the additional features can be added via plugins which enhance the project configuration in one or more of the following ways:

  • Altering the Webpack configuration (e.g. adding a new loader).
  • Altering package.json (e.g. adding a script).
  • Altering other files in the project tree (e.g. injecting markup into index.html).

Official Vue CLI 3 plugins include Typescript, PWA, Vuex, Vue Router, ESLint, unit testing, and more. These plugins, of course, provide best-practice configuration out of the box.

Installing Plugins

Installing a plugin in a Vue CLI 3 project can be done via the interactive prompt that is provided during the project initialization:

Installing plugins

However, you can install additional plugins in the project at any time in its lifecycle with the CLI command vue add my-plugin. This means you’re not limited to the choices you make at the very beginning of development.

If you have a favorite set of plugin preferences you want to use for every project, say, Vuex, TypeScript, and ESLint with Airbnb config, Vue CLI 3 allows you to save these preference in a locally stored preset file ~/.vuerc. Now you can spin up perfectly configured projects in an instant!

Webpack

The elephant in the room of any tooling software is it’s handling of Webpack.

baby serious face

When you inspect the Vue CLI 2 Webpack template config for the first time

You may be relieved when you install your first Vue CLI 3 project and see there is no webpack.config.js in the project root. This is because most project configuration for Vue CLI 3 is abstracted into plugins and is merged into the base configuration at runtime.

Tweaking the Webpack config can be done via the new vue.config.js file. For example, if you want to add a Webpack plugin (not to be confused with a Vue CLI plugin), drop the necessary code into the configureWebpack property.

vue.config.js

If you need to get fancier, there are several other APIs provided by Vue CLI 3 for Webpack config, allowing you to directly mutate it, or use the powerful webpack-chain. You can read more about Webpack config in Vue CLI 3 here.

Note: Webpack config is split among plugins and possibly vue.config.js. To see the runtime config, use the command vue inspect.

Custom Plugins

Plugins can provide their own configuration options that are specified through the pluginOptions property of vue.config.js. For example, if you use vue-cli-plugin-critical for extracting critical CSS, you can specify page width and height like this:

If you want to make more substantial changes to your project configuration, or if you want to repeat the same changes across multiple projects, you can abstract into your own custom plugin. You can then publish this on NPM if you want to share with other developers.

This kind of extensibility was possible with the template-based architecture of Vue CLI 2, as you could simply fork one of the templates and add your changes. However, this system had two serious bottlenecks:

  • Any upstream updates or bug fixes would have to be manually merged into the forked template making it laborious to maintain.
  • You’re limited to one template per project. What if there are features from several templates you want to include in a project? You’ll end up having to make your own templates with every permutation and combination of features you want, exacerbating the previous problem.

It’s for these reasons that third-party Vue CLI 2 templates never really took off. Vue CLI 3 has unequivocally overcome these limitations, so I predict a slew of cool third-party plugins to appear in addition to the official ones.

No “Ejecting”

“Ejecting” is terminology from Create React App and refers to a process where all configuration and build dependencies are moved from the scripts folder (think plugins) and placed directly into your project.

This is done to allow direct editing of the configuration. It’s a pretty inflexible system, though, as it is irreversible and prevents you from being able to receive upgrades to the scripts, even if you only needed to edit just one.

Skeleton character breaking glass

Ejecting from Create React App

And herein is the crowning achievement of Vue CLI 3: the flexibility of the plugins and configuration APIs means there is no need to eject a Vue CLI 3 project. As such, Vue CLI 3 projects will remain upgradable throughout their lifecycle.

Rapid Prototyping

If you’re like me, sometimes you’re struck by such a cool idea that you need to drop everything else and get straight to prototyping it. But if you have to then spend half an hour tinkering with Webpack and Babel config before you can get anything on the screen, it really kills the mood.

Vue CLI 3 makes it incredibly fast to go from zero to served app. It includes a Webpack dev server with hot module reloading and all the other bells and whistles you would expect.

Better yet, if Vue CLI 3 is installed globally, you can serve .js or .vue files with no local dependencies. This allows you to do something like the following:

And you’ll instantly have a Vue project on the screen.

 Using vue serve for the first time

Using vue serve for the first time

Conclusion

What I’ve covered here are just some of the new features in Vue CLI 3. There are plenty of other tasty treats like:

  • Use environment variables in your project through a .env file.
  • Build a project as a web component for use in any other JavaScript project with the command vue-cli-service build --target wc --name my-element [entry]
  • DLL mode which builds your NPM dependencies into a separate vendor bundle, improving the build time of future builds.

And more. Vue CLI 3 is still in beta at the time of writing, but why not get started now by installing it or reading the docs.

Thanks to Evan and the team for yet another fantastic tool.

What you do is very baller gif

Further Reading



Source link

Post image
Strategy

Cryptocurrency payment gateway database schema : webdev


I am trying to figure out a simplified database schema for a cryptocurrency payment gateway. It is just an intellectual exercise so it should not be bullet-proof but good enough to seem realistic.

A payment processor allowing merchants to get paid in “standard” cryptocoins like Bitcoin or Litecoin or in privacy coins like Zcash or Dash. In order to accept multiple crypto coins, upon registration the payment gateway creates a wallet (one per cryptocurrency) for the merchant, then the customer sends their favourite currency to the merchant wallet and finally the payment is forwarded to the merchant or withdrawn.

Post image

This is what I’ve come to so far, consisting of a user table with login info, a merchant expansion table for sellers and lastly the supported currencies.
For the financial part, payments are linked 1:1 to a transaction containing relevant info about the actual payment, like blockchain tx_id and confirmations. I tried to keep it quite general to avoid tight coupling to a specific coin. Wallet amounts and transaction info are obtained by querying the blockchain. The transaction table exists to allow easier control of movements of funds, especially for privacy coins.
Wallets are generated on a separate server and indexed in the db by the address.

Now, there are some noticeable problems and limitations with this db architecture.

First of all, this database schema, as for now, does not support external wallets.
Considering coins will move into the system from an external wallet (customer paying) and will go to an outer wallet (merchant withdrawing), how can I map those transactions within the database? Does the system need to map them, considering the existence of the blockchain?

Secondly, how to deal with privacy coins, where wallet amounts and transaction info isn’t public?

Lastly, where should refunding be mapped? A transaction linked to the payment or a separate table?

Thank you



Source link

Creating an Editable Webpage With Google Spreadsheets and Ta...
Strategy

Creating an Editable Webpage With Google Spreadsheets and Ta…


Please raise your hand if you’ve ever faced never-ending content revision requests from your clients. It’s not that the changes themselves are difficult, but wouldn’t it be less complicated if clients could just make the revisions themselves? That would save everyone valuable time, and  allow you to turn your attention to more important tasks.

In the case where the site is built on the flat files (e.g. HTML, CSS and JavaScript) instead of a CMS (e.g. WordPress), you’ll need some other sort of solution to edit the content without directly editing those files.

Tabletop.js allows us to use Google Spreadsheets as a sort of data store, by taking the spreadsheet and making it easily accessible through JavaScript. It provides the data from a Google Spreadsheet in JSON format, which can then use in an app, like pulling data from any other API. In this article, we’ll be adding data to a spreadsheet then setting up Tabletop so that it can pull data from the data source to our HTML. Let us get straight to the code!

This article is going to be based off a real-world site I built when I was initially trying to wrap my head around Tabletop. By the way, I always advise developers to build applications with any form of technology they’re trying to learn, even after watching or reading tutorials.

We’ll be using the demo I made, with its source code and spreadsheet . The first thing we’ll need is a Google account to access the spreadsheet. 

Open a new spreadsheet and input your own values in the columns just like mine. The first cell in on each column been the reference that’ll be used later in our JavaScript, and the second cell been the actual content for the website.

Next up, we’ll publish the data to the web by clicking on File → Publish to the web in the menu bar.

A link will be provided, but it’s technically useless to us, so we can ignore. The important thing is that the spreadsheet (and its data) is now publicly accessible so we can fetch it for our app.

That said, there is a link we need. Clicking the big green “Share” button in the upper-right corner of the page will trigger a modal that provides a sharable link to the spreadsheet and lets us set permissions as well. Let’s grab that link and set the permissions so that anyone with the link can view the spreadsheet. That way, the data won’t inadvertently be edited by someone else.

Now is the time to initialize Tabletop in our project. Let’s link up to their hosted minified file. Similarly, we could copy the raw minified code, drop it into our own script file and host it ourselves.

Here’s the document file linked up to Tabletop’s CDN and with code snagged from the documentation.

<script src='https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.5.1/tabletop.min.js'></script>

<script type='text/javascript'>    
  var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/1sbyMINQHPsJctjAtMW0lCfLrcpMqoGMOJj6AN-sNQrc/pubhtml';

  function init() {
    Tabletop.init( {
      key: publicSpreadsheetUrl,
      callback: showInfo,
      simpleSheet: true 
    } )
  }

  function showInfo(data, tabletop) {
    alert('Successfully processed!')
    console.log(data);
  }

  window.addEventListener('DOMContentLoaded', init)
</script>

Replace the publicSpreadsheetUrl variable in the code with the sharable link from the spreadsheet. See, told you we’d need that!

Now to the interesting part. Let’s give the HTML unique IDs and leave them empty. Then, inside the showInfo function, we’ll use the forEach() method to loop through each spreadsheet column while equating it with the corresponding ID.innerHTML method which, in turn, loads the spreadsheet’s data into the HTML tag through the ID.

function showInfo(data, tabletop) {
  data.forEach(function(data) {
    header.innerHTML = data.header;
    header2.innerHTML = data.header2;
    body.innerHTML = data.body;
    body2.innerHTML = data.body2;
    body3.innerHTML = data.body3;
    body4.innerHTML = data.body4;
    body5.innerHTML = data.body5;
    body6.innerHTML = data.body6;
    body7.innerHTML = data.body7;
    body8.innerHTML = data.body8;
    body9.innerHTML = data.body9;
    body10.innerHTML = data.body10;
    body11.innerHTML = data.body11;
    body12.innerHTML = data.body12;
    body13.innerHTML = data.body13;
    body14.innerHTML = data.body14;
    body15.innerHTML = data.body15;
    body16.innerHTML = data.body16;
    body17.innerHTML = data.body17;
 });
}
window.addEventListener('DOMContentLoaded', init)

This is a section of HTML from my demo showing the empty tags. This is a good way to go, but it could be abstracted further but creating the HTML elements directly from JavaScript.

<!-- Start Section One: Keep track of your snippets -->
<section class="feature">
  <div class="intro-text">
    <h3 id="body"></h3>
    <p id="body2">
      
    </p>
  </div>
  <div class="track-snippets">
    <div class="snippet-left"><img src="https://css-tricks.com/img/image-computer.png" alt="computer" /></div>
    <div class="snippet-right">
      <div>
        <h4 id="body3"></h4>
        <p id="body4">
        </p>
      </div>
      <div>
        <h4 id="body5"></h4>
        <p id="body6"></p>
      </div>
      <div>
        <h4 id="body7"></h4>
        <p id="body8">
        </p>
      </div>
    </div>
  </div>
</section>

Hey, look at that! Now we can change the content on a website in real-time by editing the content in the spreadsheet.



Source link

Slow mobile speed
Strategy

Critical CSS and Webpack: Automatically Minimize Render-Bloc…


“Eliminate render-blocking JavaScript and CSS.” It’s the one Google Page Speed Insights suggestion that I always get stuck with.

When a web page is accessed, Google wants it to only load what’s useful for the initial view, and use idle time to load anything else. That way, the user can see the page as early as possible.

Slow mobile speed

There are many things we can do to minimize render-blocking JavaScript, e.g. code splitting, tree shaking, caching, and so on.

But what about CSS? For this, we can minimize render-blocking by isolating the CSS needed for above-the-fold content (a.k.a. the critical CSS) and loading that first. We can then load the non-critical CSS afterward.

Isolating critical CSS is something that can be done programmatically, and in this article, I’ll show you how to delegate it to your Webpack pipeline.

What Does Render-Blocking Mean?

If a resource is “render-blocking,” it means the browser can’t display the page until the resource is downloaded or otherwise dealt with.

Typically, we will load our CSS in a render-blocking way by linking to our stylesheet in the head of the document, like this:

<head>
  <link rel="stylesheet" href="/style.css">
  ...
</head>
<body>
  <p>I can't be seen until style.css has been loaded!</p>
</body>

When this page is loaded by a web browser, it will read it from top to bottom. When the browser gets to the link tag, it will start downloading the stylesheet straight away, and will not render the page until it’s finished.

For a large site, particularly one with a generously-sized framework like Bootstrap, the stylesheet might be several hundred kilobytes, and the user will have to patiently wait until this fully downloads.

So, should we just link to the stylesheet in the body, where rendering is not blocked? You could, but the thing is render-blocking is not entirely bad, and we actually want to exploit it. If the page rendered without any of our CSS loaded, we’d get the ugly “flash of unstyled content”:

Sample jumbotron

The sweet-spot we want is where we render-block the page with the critical CSS that’s required to style the main view, but all non-critical CSS is loaded after the initial render.

Critical CSS

Have a look at this simple page that I’ve built with Bootstrap and Webpack. This is what it looks like after its first rendering:

Sample jumbotron

The page also has a modal that is opened by the “Sign up today” button. When opened, it looks like this:

Opening sign up modal

For the first rendering of the page, we’ll need CSS rules for the nav bar, the jumbotron, the button, and a few other general rules for layout and fonts. But we won’t need the rules for the modal since it won’t be shown immediately. With that in mind, here’s how we might isolate the critical CSS from the non-critical CSS:

critical.css

.nav {
  ...
}

.jumbtron {
  ...
}

.btn {
  ...
}

non_critical.css

.modal {
  ...
}

If you’re on board with this concept, there are two questions that you might now find of interest:

  1. How can we discern our critical and non-critical CSS programmatically?
  2. How can we get our page to load the critical CSS before the first render and load the non-critical CSS after the first render?

Example Project

I’ll briefly introduce you to the basic setup of this project, so when we reach the solution it’ll be quick to digest.

Firstly, I’m loading Bootstrap SASS into my entry file.

main.js

require("bootstrap-sass/assets/stylesheets/_bootstrap.scss");

I’m using sass-loader to handle this, and I’m using it in conjunction with the Extract Text Plugin so that the compiled CSS goes into its own file.

I’m also using the HTML Webpack Plugin to create an HTML file in the build. It’s necessary for the solution, as you’ll soon see.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader']
        })
      },
      ...
    ]
  },
  ...
  plugins: [
    new ExtractTextPlugin({ filename: 'style.css' }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    })
  ] 
};

After I run a build, here’s what the HTML file looks like. Note that CSS is being loaded in the head and will, therefore, block rendering.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>vuestrap-code-split</title>
    <link href="/style.css" rel="stylesheet">
</head>
<body>
  <!--App content goes here, omitted for brevity.-->
  <script type="text/javascript" src="/build_main.js"></script>
</body>
</html>

Programmatically Identifying Critical CSS

Manually identifying the critical CSS would be a pain to maintain. To do it programmatically, we can use Addy Osmani’s aptly named Critical. This is a Node.js module that will read in an HTML document, and identify the critical CSS. It does a bit more than that as well, as we’ll see shortly.

The way that Critical identifies the critical CSS is by loading the page with PhantomJS, with a screen dimension you specify, and by extracting any CSS rules used in the rendered page.

Here’s how we can set it up for this project:

const critical = require("critical");

critical.generate({

  /* The path of the Webpack bundle */
  base: path.join(path.resolve(__dirname), 'dist/'),
  src: 'index.html',
  dest: 'index.html',
  inline: true,
  extract: true,

  /* iPhone 6 dimensions, use whatever you like*/
  width: 375,
  height: 565,

  /* Ensure that bundled JS file is called */
  penthouse: {
    blockJSRequests: false,
  }
});

When executed, this will update the HTML file in the Webpack bundle output to:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Bootstrap Critical</title>
  <style type="text/css">
    /* Critical CSS is inlined into the document head, abbreviated here. */
    body {
      font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
      font-size: 14px;
      line-height: 1.42857;
      color: #333;
      background-color: #fff;
    }
    ...
  </style>
  <link href="/style.96106fab.css" rel="preload" as="style" onload="this.rel='stylesheet'">
  <noscript>
      <link href="/style.96106fab.css" rel="stylesheet">
  </noscript>
  <script>
    /*A script for loading the non-critical CSS goes here, omitted for brevity.*/
  </script>
</head>
<body>
  <!--App content goes here, omitted for brevity.-->
  <script type="text/javascript" src="/build_main.js"></script>
</body>
</html>

It will also output a new CSS file, e.g. style.96106fab.css (a hash is automatically added to the file name). This CSS file is the same as the original stylesheet, only with critical CSS stripped out.

Inlining Critical CSS

You’ll notice that the critical CSS has been inlined into the head of the document. This is optimal as the page doesn’t have to load it from the server.

Preload Non-Critical CSS

You’ll also notice that the non-critical CSS is loaded with a sophisticated-looking link. The preload value tells the browser to start fetching the non-critical CSS for pending use. But crucially, preload is not render-blocking, so the browser will go ahead and paint the page whether the preload resource is completed or not.

The onload attribute in the link allows us to run a script when the non-critical CSS has eventually loaded. The Critical module automatically inlines a script into the document that provides a cross-browser compatible way of loading the non-critical stylesheet into the page.

<link href="/style.96106fab.css" rel="preload" as="style" onload="this.rel='stylesheet'">

Putting Critical Into a Webpack Pipeline

I’ve made a Webpack plugin called HTML Critical Webpack Plugin that is merely a wrapper for the Critical module. It will run after your files have been emitted from the HTML Webpack Plugin.

Here’s how you can include it in a Webpack project:

const HtmlCriticalPlugin = require("html-critical-webpack-plugin");

module.export = {
  ...
  plugins: [
    new HtmlWebpackPlugin({ ... }),
    new ExtractTextPlugin({ ... }),
    new HtmlCriticalPlugin({
      base: path.join(path.resolve(__dirname), 'dist/'),
      src: 'index.html',
      dest: 'index.html',
      inline: true,
      minify: true,
      extract: true,
      width: 375,
      height: 565,
      penthouse: {
        blockJSRequests: false,
      }
    })
  ] 
};

Note: you should probably only use this in a production build, not development, as it will make your build really slow!

Performance Results

Now that I’ve isolated critical CSS, and I’m loading the non-critical CSS in idle time, what do I get in the way of performance improvements?

I used the Chrome Lighthouse extension to find out. Keep in mind the metric we’re trying to optimize is Time To First Meaningful Paint, which basically tells us how long it is until the user can see something.

Before implementing critical CSS:

Base performance before critical CSS

After implementing critical CSS:

Base metrics post-critical CSS

As you can see, my app got a meaningful paint a full second earlier and is interactive half a second earlier. In practice, you may not get such a dramatic improvement in your app, since my CSS was thoroughly bloated (I included the entire Bootstrap library), and in such a simple app I didn’t have many critical CSS rules.

Become a senior Vue developer in 2020.

Learn and master what professionals know about building, testing, and deploying, full-stack Vue apps in our latest course.

Learn more



Source link

Post image
Strategy

Backing up site with Filezilla and xml files won’t transfer …


So I’m in charge of launching our new site via ftp to the server. I did a backup yesterday and 105 files didn’t transfer. They were all xml files and the error was 550 so I assume I don’t have the permissions.

I also have to take everything off the server before uploading as per my school district’s IT dept. I assume I’m going to have the same problem taking them off.

Any suggestions? I’d have to go through district IT to do anything that requires admin permission. Thanks to ransomware issues in schools lately not even our school IT guy has admin permission.

Also, if I just take all of the folders off the server and upload my folders, it’s gonna work?

I’ve never done any of this before and it’s freaking me out a little bit.

Post image



Source link

chrome_1.gif
Strategy

What I Learned About VueJS From Building A Chrome Extension


I wanted to experiment with building a Google Chrome extension with Vue.js so I decided to take the Vue TodoMVC and try to make it accessible from my browser toolbar:

chrome_1.gif

Building a browser extension with Vue is a very similar process to building a regular web page with Vue, but there are a few key differences which I’ll discuss in this article.

No Templates

One thing we love about Vue is the ability to use templates either in a file:

<body>
  <div id="app">
    <div>{{ message }}</div>
  </div>
</body>

Or in a string:

new Vue({
  template: `<div>{{ message }}</div>`
});

One small problem: you can’t use templates like this in Chrome extensions!

But before you give up and go back to jQuery, it’s worth understanding why this limitation exists and how Vue can help you work around it.

Browser Extensions Are Like Web Pages Only Different

Browser extensions use HTML, CSS, and JavaScript just like regular web pages. But there are APIs that extensions can access that web pages can’t, allowing them to extend the features of bookmarks, dev tools, and other browser aspects.

This additional access makes users more vulnerable to security holes though, so extensions require a Content Security Policy to make them more secure by disabling potentially unsafe features.

Content Security Policy (CSP)

No one likes to read about policies, so I’ll keep this brief: among other things, the CSP imposes restrictions on the kind of code that your extension can include:

  • Inline scripts are disabled e.g. <button onclick="...">
  • Content must be loaded locally, i.e. no scripts via CDN.
  • eval functions are disabled e.g. eval("alert(('hi')")

It’s this last restriction on eval functions that affects us Vue users.

Note: eval is considered unsafe as it can be used to run arbitrary code and make your application vulnerable to cross-scripting attacks.

How Vue Templates Are Compiled

At runtime, Vue’s internal template compiler will parse the document or template string and generate a JavaScript representation of the template.

Vue’s efficiency gains are partly due to its ability to make manipulations in JavaScript before making them directly to the page.

Unfortunately, the template compiler relies on eval functions to perform this compilation task, and these are not allowed under the CSP.

Solution 1: Allow “unsafe-eval” (Not Recommended)

You can actually override the eval restriction in your extension’s CSP, and that would solve the problem. However, it is not recommended as it now makes your extension vulnerable to cross-script attacks.

Solution 2: Don’t Compile Templates at Runtime

We can actually build a Vue app just fine without the runtime template compiler (FYI the compiler is an internal library called vue-template-compiler that can be used standalone).

If you’ve used Vue as an ES6 module then you may have already been doing this but perhaps didn’t realize that’s what you were doing!

As discussed, Vue’s template compiler is used whenever you use a template string, like so:

new Vue({
  template: `<div>{{ message }}</div>`
});

Or, when you mount to a template using el:

new Vue({
  el: '#app'
}); 
<body>
  <div id="app">
    <div>{{ message }}</div>
  </div>
</body>

In both those scenarios, Vue must parse the string <div>{{ message }}</div> and that’s where an eval function is used.

Render Functions

Render functions are JavaScript functions that can be used to generate a template. If you use a render function to create your template, the template compiler is not needed:

new Vue({
  render (createElement) {
    return createElement('div', this.message)
  }
}).$mount('#app');
<body>
  <div id="app"></div>
</body>

Note: Using an empty node to mount to does not invoke the template compiler.

But…Render Functions Are Hard to Use

It’s true, render functions are not an intuitive way to create templates.

But don’t worry, you won’t have to manually write your render functions. Instead, you can use the template compiler in development to precompile your templates into render functions.

Obviously, the CSP doesn’t mind if you compile a template, it’s doing it at runtime with eval – that’s the issue.

Note: you can use JSX to make your render functions if you’re that way inclined.

Single File Components to the Rescue

There’s yet another reason why single file components (SFCs) are awesome: they’re precompiled and therefore CSP compliant.

When you use vue-loader to process your .vue file, one of the things it does is use vue-template-compiler to turn your component’s template into a render function.

So if you have an SFC with this template:

<template>
  <div id="app">{{ message }}</div>
</template>

After you build, look in your Webpack bundle and you’ll see something like this:

render: function () {
  return this.$createElement("div", {attrs: {id: "app"}}, [this.message])
}

If your whole app is comprised of single file components Vue will not need to do any runtime template compilation.

Runtime-Only Build

You may have noticed in the Vue docs something about a “full build” and a “runtime-only” build. If you’re like me you probably skipped that part!

The runtime-only build is the same as the full build only withoutvue-template-compiler. If your app templates have been precompiled, you should use this runtime-only build. Not only is it CSP compliant, but it’s also 30% lighter!

In an ES5 setup you can load the runtime-only Vue library like this:

<script src="vue.runtime.min.js"></script>

But more likely you’ll be using an ES6 setup with Webpack and you’ll want this

import Vue from 'vue'

to refer to the runtime build, not the full build. Fortunately, it does this by default!



Source link

Flexmonster example
Strategy

Comparison of JavaScript Pivot Grids for Developers


In this article, I’d like to consider the most popular JavaScript pivot grid components. During this review, I won’t dive into the coding since each grid has exhaustive and well-written documentation (at least, I hope so). Instead, I’ll focus on the core features of each pivot grid. Since I believe that there are some beginner developers among the readers, I’ll pay particular attention to documentation and demo pages. It’s a pretty convenient way to learn something while having a working example before your eyes. Therefore, demo pages with code examples and detailed descriptions will be a plus.

The principle of pivots selection is simple. I’ll check the most popular of those that can be used as stand-alone components. The reason is that I’m looking for relatively cheap and lightweight options leaving complex solutions for the future articles. So, let’s take a look at the list of JavaScript pivot grids I’m going to review today:

  1. Flexmonster

  2. PivotTable.js

  3. dhtmlxPivot

  4. Orb.js

  5. WebPivotTable Component

  6. jbPivot

  7. Webix

1. Flexmonster

Flexmonster example

Flexmonster example

Flexmonster is a pivot table component that works on main desktop and mobile operating systems such as Windows, macOS, Linux, iOS, and Android. The cross-browser support allows running Flexmonster based applications in Chrome, Firefox, Internet Explorer, Safari, or Opera without any additional plugins such as Flash or Java. The list of supported server-side technologies includes .NET, Java, PHP, Ruby, and many others. If you work with one of the popular frameworks such as jQuery, Angular, React, RequireJS, or PhoneGap, you’ll like the integration possibilities. Another distinctive feature is the availability of wrappers for TypeScript, C#, and Java. As you can see, this pivot table can be integrated with almost any project due to wide support of modern web development technologies. One of the main intentions of developers was to provide the possibility to work with huge amounts of data. As a result, using this JavaScript pivot grid, you can work with big data sets from SQL DBs or files up to 100 MB. You can be assured that rendering even millions of rows won’t cause any freezes or lags.

The number of supported data formats won’t disappoint you either. You can work with CSV, JSON, SQL databases (Oracle, MySQL, etc.), XMLA providers (MS Analysis Services, Mondrian, and icCube). This component is fully customizable due to its rich API. There’s the possibility to define what features will be enabled or disabled. As well, you can build your custom scenarios around the component. API covers every aspect of data presentation. All settings can be stored in a report object which can be saved and restored if needed.

Flexmonster provides users with dozens of handy features. For example, there are three ways of filtering:

  • Filtering by members’ names, users can choose which exact members will be shown for a particular field.

  • Filter by value returns top X results.

  • Report filter can be used for convenient data representation in reports. It allows you to focus on important data subsets and avoid overloading with large amounts of unnecessary info.

The sorting feature allows placing rows and columns in alphabetical or numeric order. The grouping feature allows saving some screen space which is especially helpful in the case of mobile devices. The built-in exporting feature allows exporting your table to the following formats: HTML, CSV, Excel, PDF, and PNG.

This component supports different types of formatting:

  • Conditional formatting allows highlighting cells depending on particular values.

  • Number formatting is convenient for changing the appearance of numbers, without actual changing of value. You can add currency symbols or decimal separators.

The demo page contains a lot of examples each of which is explained in detail. The source code for each demo is available on JSFiddle. The documentation page is pretty detailed and contains a lot of step-by-step guides, code examples, and some screenshots. Looks like a great component indeed! But unfortunately, it’s not a free tool. The annual subscription will cost you $799. Perpetual license, in its turn, costs $1999.

You may also like:
4 Free Web Pivot Tables You Should Try for Your Web Reporting.

2. PivotTable.js

PivotTable.js example

PivotTable.js example

PivotTable.js is a lightweight open-source JavaScript Pivot Table with the drag-n-drop support. This component allows changing the appearance by re-defining the initial color set and using a custom color scale. Almost every part of this pivot grid can be customized with ease. For example, the localization process is quite simple and well-described in the documentation. The input data is a set of records with attributes. It can be passed to the app in different ways: CSV files, arrays of objects, arrays of arrays, functions that call back, or jQuery references to simple tables.

In addition to the built-in table, heat map, and table-bar chart renderers, PivotTable.js allows creating different types of charts. You can use either C3 Charts, D3 Visualizations, or Google Charts for such tasks. Unfortunately, currently, there’s no feature that allows you to export to an Excel file. But you can generate TSV output similar to the Table Renderer, which, in turn, can be copy-pasted to Excel. This component was initially designed to be a client-side component. It requires all the data to be supplied up front in the browser. Thus, you can integrate this library with any server-side technology which is able to provide data in a compatible format, but there is no ‘deep’ integration beyond the original data load.

The main page of the project contains a bunch of demos, each of which has the basic description and source code. The documentation wiki describes the use of the main parameters and features. In general, I can say that the documentation is rather modest. But since PivotTable.js is a pretty simple and minimalistic component, it’s unlikely that you will face any difficulties. This pivot grid is a free-to-use tool and distributed under the MIT license.

3. dhtmlxPivot

dhtmlxPivot

dhtmlxPivot example

The dhtmlxPivot JavaScript component is a fully-customizable pivot grid intended for rendering huge amounts of data. Despite the size of the dataset used, your app will run smoothly on all browsers. You can customize each aspect of this pivot by modifying one of the available attributes. To simplify the work with this component, developers are provided the possibility to load data in JSON format. Besides that, you can use CSV, the same format that the Google Spreadsheet uses. To load data that is stored on the server, you can use Java, .NET, PHP, Node.js, and other technologies.

Using aliases, you can make a data set more compact by reducing the number of duplicate data values. Conditional cell formatting allows for the highlighting those cells that have particular values. You can filter the content of cells in accordance with the type of data they contain. There are three different filters:

  • String filter

  • Number filter

  • Dates filter

By default, dhtmlxPivot supports four basic operations (sum, max, min, and count), but if needed, you can add custom ones. When you click on the header of the row, a sorting icon will appear on the screen in order to help you to sort the listed data according to your needs. The exporting feature allows exporting your tables to the Excel files. It’s worth noting that all custom styles that were added during the work with the table will be exported as well.

The documentation page is quite exhaustive. It has a step-by-step Getting Started guide for those who are just starting to work with this component, a bunch of more advanced guides, and detailed API references. The demos page contains samples that demonstrate the most important features of this pivot table. I can say that dhtmlxPivot is the most well-documented JavaScript component among the other ones mentioned in this article. If you decide to try it, there’s the Free Trial edition available. Besides that, there are two more options. The Commercial license for teams of five or fewer developers will cost you $299. The Enterprise license, which includes extended support, costs $499 at the moment. Among the pivot components that are distributed under a commercial license, dhtmlxPivot is the most affordable option.

4. Orb.js

Orb.js example

Orb.js example

Orb.js is a React-based library for creating pivot grid apps. It provides users with all the required features. The drag-and-drop oriented interface allows for the moving of fields between the axes using the cursor. You can sort the content of a column, use filtering, and drill down into the pivot grid data. Orb.js can evaluate grand totals and subtotals. You can enable fixed headers. The exporting feature allows you to export your table to Excel. This component is fully customizable.

As you can see, there’s nothing fancy here. Only the basic features required for developing a neat, minimalistic, and fast pivot grid. The documentation is not very extensive and does not contain any demos or screenshots that demonstrate what result you’ll get following the instructions. As you might have guessed, this component is a free-to-use tool and distributed under the MIT license.

5. WebPivotTable

WebPivotTable

WebPivotTable example

The WebPivotTable component is a pivot table for data analysis and report creation that mimics the behavior of Microsoft Excel. It works in all modern browsers such as Firefox, Chrome, Opera, Safari, and Internet Explorer. Among the supported operating systems, there are Windows, iOS, and Android. The drag-and-drop interface, along with the familiar user interface, makes it pretty easy to use for those who have some experience with Excel. It can run independently, or you can integrate it with your website or web application. This component supports different types of data such as CSV/XLS/XLSX data and Google spreadsheet. As well, you can load CSV data from a local drive, the Internet, or cloud drives. WebPivotTable allows you to create visualizations in the form of charts and it has great basic features such as filtering, sorting, formatting, and layout changes. The exporting feature supports a wide variety of file formats: PDF, Excel HTML, JPEG, and PNG. You can drill through the data by just clicking.

To be honest, I can’t say that the documentation page is able to answer all the questions that may appear during the work with this component. It includes a Quick Start Guide, important info on customization and other aspects, but it’s not as detailed as one can expect. WebPivotTable is distributed under two licenses. You can choose a free edition with limited functionality or go for the Component Edition which will cost you $1,499.

6. jbPivot

jbPivot

jbPivot example

jbPivot is a simple jQuery pivot table widget. This one is, probably, the most minimalistic pivot table component among the other examples. You can install it using the npm package manager, and it doesn’t require much effort to get started. The drag-and-drop oriented user interface allows dragging the fields to any axis. There’s the possibility to add records to the table dynamically if needed. The sorting feature allows you to specify whether you want to sort the table items in ascending or descending order. There’s also the possibility to define the custom grouping criteria.

The documentation page does not contain any deep explanations. You’ll only learn how to initialize the component on the page. If you don’t have any previous experience with the pivot tables, it’ll be hard to understand how everything works. However, it’s a pretty good choice if you’re looking for a fast jQuery plugin for creating a pivot table on the page. There’s no exporting or any other complex feature of such kind. But if you’re dealing with small amounts of data, jbPivot will work just fine for you. This component is a free-to-use tool. It’s distributed under the GPLv3 license.

7. Webix Pivot Table

Webfix pivot table

Webfix pivot table

Webix JavaScript Pivot Table widget performs data aggregation. It extracts significant information from extensive datasets. Pivot easily arranges, compares and summarizes complex data. The component is fully customizable. It’s possible to change datatable settings, create custom functions for data structuring, adjust filters, customize the configuration window, etc. With Webix Pivot widget you can export data to a number of formats such as PNG, Excel, CSV, PDF. Moreover, you can apply a custom locale to the page and set a different language.

Webix Pivot has a variety of advanced features such as filtering, sorting, cell highlighting, quick configuring, row and column totals, and many others.

The widget supports all platforms and browsers. The widget can be integrated with Vue.js,  AngularJS, jQuery, React, and other third-party libraries. There is a backend integration with .NET, PHP, and Node.js.

Webix is available as a free outsource library but you can also buy a Commercial license.

Further Reading



Source link