Optimize your jQuery selectors for best performance

Introduction Over time, the data size has increased for nearly every application. Due to huge amount of data residing in various database servers, performance becomes the most important and integral part of any application. If the page takes lots of time to render the data, it creates a bad impression and results in loss of […]

Link: http://feedproxy.google.com/~r/LearningJquery/~3/Dc5XLqV2kmA/optimize-your-jquery-selectors-for-best-performance-2

Help Your Users `Save-Data`

The breadth and depth of knowledge to absorb in the web performance space is ridiculous. At a minimum, I’m discovering something new nearly every week. Case in point: The Save-Data header, which I discovered via a Google Developers article by Ilya Grigorik.
If you’re looking for the tl;dr version of how Save-Data works, let me oblige you: If you use Chrome’s Data Saver extension on your desktop device or opt into data savings on the Android version of …

Help Your Users `Save-Data` is a post from CSS-Tricks

Link: https://css-tricks.com/help-users-save-data/

Cache Busting Front-end Resources: Is File Name Revving Still Necessary?

This just in: Web developers are easily swayed by tentacled sea creatures. But wait, I’m getting ahead of myself. I’ll get back to that in a moment.
Caching and cache-busting front-end resources have been common for a number of years now. When dealing with front-end resources, you want to be able to accomplish two things:

Link: https://www.impressivewebs.com/cache-busting-front-end-resources-file-name-revving-still-necessary/

Procedurally Generated Game Terrain with React, PHP, and WebSockets

Last time, I began telling you the story of how I wanted to make a game. I described how I set up the async PHP server, the Laravel Mix build chain, the React front end, and WebSockets connecting all this together. Now, let me tell you about what happened when I starting building the game mechanics with this mix of React, PHP, and WebSockets…

The code for this part can be found at github.com/assertchris-tutorials/sitepoint-making-games/tree/part-2. I’ve tested it with PHP 7.1, in a recent version of Google Chrome.

Making a Farm
“Let’s start simple. We have a 10 by 10 grid of tiles, filled with randomly generated stuff."
I decided to represent the farm as a Farm, and each tile as a Patch. From app/Model/FarmModel.pre:
namespace App\Model;

class Farm
{
private $width
{
get { return $this->width; }
}

private $height
{
get { return $this->height; }
}

public function __construct(int $width = 10,
int $height = 10)
{
$this->width = $width;
$this->height = $height;
}
}

I thought it would be a fun time to try out the class accessors macro by declaring private properties with public getters. For this I had to install pre/class-accessors (via composer require).
I then changed the socket code to allow for new farms to be created on request. From app/Socket/GameSocket.pre:
namespace App\Socket;

use Aerys\Request;
use Aerys\Response;
use Aerys\Websocket;
use Aerys\Websocket\Endpoint;
use Aerys\Websocket\Message;
use App\Model\FarmModel;

class GameSocket implements Websocket
{
private $farms = [];

public function onData(int $clientId,
Message $message)
{
$body = yield $message;

if ($body === "new-farm") {
$farm = new FarmModel();

$payload = json_encode([
"farm" => [
"width" => $farm->width,
"height" => $farm->height,
],
]);

yield $this->endpoint->send(
$payload, $clientId
);

$this->farms[$clientId] = $farm;
}
}

public function onClose(int $clientId,
int $code, string $reason)
{
unset($this->connections[$clientId]);
unset($this->farms[$clientId]);
}

// …
}

I noticed how similar this GameSocket was to the previous one I had — except, instead of broadcasting an echo, I was checking for new-farm and sending a message back only to the client that had asked.
"Perhaps it’s a good time to get less generic with the React code. I’m going to rename component.jsx to farm.jsx."
From assets/js/farm.jsx:
import React from "react"

class Farm extends React.Component
{
componentWillMount()
{
this.socket = new WebSocket(
"ws://127.0.0.1:8080/ws"
)

this.socket.addEventListener(
"message", this.onMessage
)

// DEBUG

this.socket.addEventListener("open", () => {
this.socket.send("new-farm")
})
}
}

export default Farm

In fact, the only other thing I changed was sending new-farm instead of hello world. Everything else was the same. I did have to change the app.jsx code though. From assets/js/app.jsx:
import React from "react"
import ReactDOM from "react-dom"
import Farm from "./farm"

ReactDOM.render(
,
document.querySelector(".app")
)

It was far from where I needed to be, but using these changes I could see the class accessors in action, as well as prototype a kind of request/response pattern for future WebSocket interactions. I opened the console, and saw {"farm":{"width":10,"height":10}}.
"Great!"
Then I created a Patch class to represent each tile. I figured this was where a lot of the game’s logic would happen. From app/Model/PatchModel.pre:
namespace App\Model;

class PatchModel
{
private $x
{
get { return $this->x; }
}

private $y
{
get { return $this->y; }
}

public function __construct(int $x, int $y)
{
$this->x = $x;
$this->y = $y;
}
}

I’d need to create as many patches as there are spaces in a new Farm. I could do this as part of FarmModel construction. From app/Model/FarmModel.pre:
namespace App\Model;

class FarmModel
{
private $width
{
get { return $this->width; }
}

private $height
{
get { return $this->height; }
}

private $patches
{
get { return $this->patches; }
}

public function __construct($width = 10, $height = 10)
{
$this->width = $width;
$this->height = $height;

$this->createPatches();
}

private function createPatches()
{
for ($i = 0; $i < $this->width; $i++) {
$this->patches[$i] = [];

for ($j = 0; $j < $this->height; $j++) {
$this->patches[$i][$j] =
new PatchModel($i, $j);
}
}
}
}

For each cell, I created a new PatchModel object. These were pretty simple to begin with, but they needed an element of randomness — a way to grow trees, weeds, flowers … at least to begin with. From app/Model/PatchModel.pre:
public function start(int $width, int $height,
array $patches)
{
if (!$this->started && random_int(0, 10) > 7) {
$this->started = true;
return true;
}

return false;
}

I thought I’d begin just by randomly growing a patch. This didn’t change the external state of the patch, but it did give me a way to test how they were started by the farm. From app/Model/FarmModel.pre:
namespace App\Model;

use Amp;
use Amp\Coroutine;
use Closure;

class FarmModel
{
private $onGrowth
{
get { return $this->onGrowth; }
}

private $patches
{
get { return $this->patches; }
}

public function __construct(int $width = 10,
int $height = 10, Closure $onGrowth)
{
$this->width = $width;
$this->height = $height;
$this->onGrowth = $onGrowth;
}

public async function createPatches()
{
$patches = [];

for ($i = 0; $i < $this->width; $i++) {
$this->patches[$i] = [];

for ($j = 0; $j < $this->height; $j++) {
$this->patches[$i][$j] = $patches[] =
new PatchModel($i, $j);
}
}

foreach ($patches as $patch) {
$growth = $patch->start(
$this->width,
$this->height,
$this->patches
);

if ($growth) {
$closure = $this->onGrowth;
$result = $closure($patch);

if ($result instanceof Coroutine) {
yield $result;
}
}
}
}

// …
}

There was a lot going on here. For starters, I introduced an async function keyword using a macro. You see, Amp handles the yield keyword by resolving Promises. More to the point: when Amp sees the yield keyword, it assumes what is being yielded is a Coroutine (in most cases).
I could have made the createPatches function a normal function, and just returned a Coroutine from it, but that was such a common piece of code that I might as well have created a special macro for it. At the same time, I could replace code I had made in the previous part. From helpers.pre:
async function mix($path) {
$manifest = yield Amp\File\get(
.."/public/mix-manifest.json"
);

$manifest = json_decode($manifest, true);

if (isset($manifest[$path])) {
return $manifest[$path];
}

throw new Exception("{$path} not found");
}

Previously, I had to make a generator, and then wrap it in a new Coroutine:
use Amp\Coroutine;

function mix($path) {
$generator = () => {
$manifest = yield Amp\File\get(
.."/public/mix-manifest.json"
);

$manifest = json_decode($manifest, true);

if (isset($manifest[$path])) {
return $manifest[$path];
}

throw new Exception("{$path} not found");
};

return new Coroutine($generator());
}

I began the createPatches method as before, creating new PatchModel objects for each x and y in the grid. Then I started another loop, to call the start method on each patch. I would have done these in the same step, but I wanted my start method to be able to inspect the surrounding patches. That meant I would have to create all of them first, before working out which patches were around each other.
I also changed FarmModel to accept an onGrowth closure. The idea was that I could call that closure if a patch grew (even during the bootstrapping phase).
Each time a patch grew, I reset the $changes variable. This ensured the patches would keep growing until an entire pass of the farm yielded no changes. I also invoked the onGrowth closure. I wanted to allow onGrowth to be a normal closure, or even to return a Coroutine. That’s why I needed to make createPatches an async function.
Note: Admittedly, allowing onGrowth coroutines complicated things a bit, but I saw it as essential for allowing other async actions when a patch grew. Perhaps later I’d want to send a socket message, and I could only do that if yield worked inside onGrowth. I could only yield onGrowth if createPatches was an async function. And because createPatches was an async function, I would need to yield it inside GameSocket.
"It’s easy to get turned off by all the things that need learning when making one’s first async PHP application. Don’t give up too soon!"
The last bit of code I needed to write to check that this was all working was in GameSocket. From app/Socket/GameSocket.pre:
if ($body === "new-farm") {
$patches = [];

$farm = new FarmModel(10, 10,
function (PatchModel $patch) use (&$patches) {
array_push($patches, [
"x" => $patch->x,
"y" => $patch->y,
]);
}
);

yield $farm->createPatches();

$payload = json_encode([
"farm" => [
"width" => $farm->width,
"height" => $farm->height,
],
"patches" => $patches,
]);

yield $this->endpoint->send(
$payload, $clientId
);

$this->farms[$clientId] = $farm;
}

This was only slightly more complex than the previous code I had. I needed to provide a third parameter to the FarmModel constructor, and yield $farm->createPatches() so that each could have a chance to randomize. After that, I just needed to pass a snapshot of the patches to the socket payload.

Random patches for each farm

"What if I start each patch as dry dirt? Then I could make some patches have weeds, and others have trees …"
I set about customizing the patches. From app/Model/PatchModel.pre:
private $started = false;

private $wet {
get { return $this->wet ?: false; }
};

private $type {
get { return $this->type ?: "dirt"; }
};

public function start(int $width, int $height,
array $patches)
{
if ($this->started) {
return false;
}

if (random_int(0, 100) < 90) {
return false;
}

$this->started = true;
$this->type = "weed";

return true;
}

I changed the order of logic around a bit, exiting early if the patch had already been started. I also reduced the chance of growth. If neither of these early exits happened, the patch type would be changed to weed.
I could then use this type as part of the socket message payload. From app/Socket/GameSocket.pre:
$farm = new FarmModel(10, 10,
function (PatchModel $patch) use (&$patches) {
array_push($patches, [
"x" => $patch->x,
"y" => $patch->y,
"wet" => $patch->wet,
"type" => $patch->type,
]);
}
);

Continue reading %Procedurally Generated Game Terrain with React, PHP, and WebSockets%

Link: https://www.sitepoint.com/procedurally-generated-game-terrain-reactjs-php-websockets/

Game Development with React and PHP: How Compatible Are They?

“I’d like to make a multiplayer, economy-based game. Something like Stardew Valley, but with none of the befriending aspects and a player-based economy."
I started thinking about this the moment I decided to try and build a game using PHP and React. The trouble is, I knew nothing about the dynamics of multiplayer games, or how to think about and implement player-based economies.

I wasn’t even sure I knew enough about React to justify using it. I mean, the initial interface — where I focus heavily on the server and economic aspects of the game — is perfectly suited for React. But what about when I start to make the farming /interaction aspects? I love the idea of building an isometric interface around the economic system.
I once watched a talk by dead_lugosi, where she described building a medieval game in PHP. Margaret inspired me, and that talk was one of the things that led to me writing a book about JS game development. I became determined to write about my experience. Perhaps others could learn from my mistakes in this case, too.

The code for this part can be found at: github.com/assertchris-tutorials/sitepoint-making-games/tree/part-1. I’ve tested it with PHP 7.1 and in a recent version of Google Chrome.

Setting Up the Back End
The first thing I searched for was guidance on building multiplayer economies. I found an excellent Stack Overflow thread in which folks explained various things to think about. I got about halfway through it before realizing I may have been starting from the wrong place.
"First things first: I need a PHP server. I’m going to have a bunch of React clients, so I want something capable of high-concurrency (perhaps even WebSockets). And it needs to be persistent: things must happen even when players aren’t around."
I went to work setting up an async PHP server — to handle high concurrency and support WebSockets. I added my recent work with PHP preprocessors to make things cleaner, and made the first couple of endpoints.
From config.pre:
$host = new Aerys\Host();
$host->expose("*", 8080);

$host->use($router = Aerys\router());
$host->use($root = Aerys\root(.."/public"));

$web = process .."/routes/web.pre";
$web($router);

$api = process .."/routes/api.pre";
$api($router);

I decided to use Aerys for the HTTP and WebSocket portions of the application. This code looked very different from the Aerys docs, but that’s because I had a good idea about what I needed.
The usual process for running an Aerys app was to use a command like this:
vendor/bin/aerys -d -c config.php

That’s a lot of code to keep repeating, and it didn’t handle the fact that I wanted to use PHP preprocessing. I created a loader file.
From loader.php:
return Pre\processAndRequire(__DIR__ . "/config.pre");

I then installed my dependencies. This is from composer.json:
"require": {
"amphp/aerys": "dev-amp_v2",
"amphp/parallel": "dev-master",
"league/container": "^2.2",
"league/plates": "^3.3",
"pre/short-closures": "^0.4.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
},

I wanted to use amphp/parallel, to move blocking code out of the async server, but it wouldn’t install with a stable tag of amphp/aerys. That’s why I went with the dev-amp_v2 branch.
I thought it would be a good idea to include some sort of template engine and service locator. I opted for PHP League versions of each. Finally I added pre/short-closures, both to handle the custom syntax in config.pre and the short closures I planned on using after…
Then I set about creating routes files. From routes/web.pre:
use Aerys\Router;
use App\Action\HomeAction;

return (Router $router) => {
$router->route(
"GET", "/", new HomeAction
);
};

And, from routes/api.pre:
use Aerys\Router;
use App\Action\Api\HomeAction;

return (Router $router) => {
$router->route(
"GET", "/api", new HomeAction
);
};

Though simple routes, these helped me to test the code in config.pre. I decided to make these routes files return closures, so I could pass them a typed $router, to which they could add their own routes. Finally, I created two (similar) actions.
From app/Actions/HomeAction.pre:
namespace App\Action;

use Aerys\Request;
use Aerys\Response;

class HomeAction
{
public function __invoke(Request $request,
Response $response)
{
$response->end("hello world");
}
}

One final touch was to add shortcut scripts, to launch dev and prod versions of the Aerys server.
From composer.json:
"scripts": {
"dev": "vendor/bin/aerys -d -c loader.php",
"prod": "vendor/bin/aerys -c loader.php"
},
"config": {
"process-timeout": 0
},

With all of this done, I could spin up a new server, and visit http://127.0.0.1:8080 just by typing:
composer dev

Continue reading %Game Development with React and PHP: How Compatible Are They?%

Link: https://www.sitepoint.com/game-development-with-reactjs-and-php-how-compatible-are-they/

Observing Intersection Observers

As developing for the web has matured and JavaScript engines have become faster, one area remains a significant bottleneck – rendering. It’s because of this that so many of the recent development efforts have been focused around rendering, with virtual DOM being one of the more popular examples. In Dojo 2, being aware of these […]
The post Observing Intersection Observers appeared first on David Walsh Blog.

Link: https://davidwalsh.name/intersection-observers

Using the Paint Timing API

It’s a great time to be a web performance aficionado, and the arrival of the Paint Timing API in Chrome 60 is proof positive of that fact. The Paint Timing API is yet another addition to the burgeoning Performance API, but instead of capturing page and resource timings, this new and experimental API allows you to capture metrics on when a page begins painting.
If you haven’t experimented with any of the various performance APIs, it may help if …

Using the Paint Timing API is a post from CSS-Tricks

Link: https://css-tricks.com/paint-timing-api/

Detect WEBP Support with JavaScript

Image optimization is a huge part of improving front-end performance.  We’ve traditionally used JPG/JPEG, GIF, and PNG images but Google and the Chrome team developed the WEBP format which crunches file size and optimizes rendering.  If you go to a site like GIPHY in Chrome you’ll be served a WEBP, but if you go to […]
The post Detect WEBP Support with JavaScript appeared first on David Walsh Blog.

Link: https://davidwalsh.name/detect-webp

The Critical Request

Serving a website seems pretty simple: Send some HTML, the browser figures out what resources to load next. Then we wait patiently for the page to be ready.
Little may you know, a lot is going on under the hood.
Have you ever wondered how browser figures out which assets should be requested and in what order?
Today we’re going to take a look at how we can use resource priorities to improve the speed of delivery.

The Critical Request is a post from CSS-Tricks

Link: https://css-tricks.com/the-critical-request/

Optimizing Performance of A-Frame Scenes for Mobile Devices

For a WebVR capstone project at Oregon State University, our team investigated performance and optimizations for A-Frame on Android smartphones. We developed a means of benchmarking the level of 3D complexity a mobile phone is capable of, and determining which performance metrics are required for such a benchmark.

Link: https://hacks.mozilla.org/2017/07/optimizing-performance-of-a-frame-scenes-for-mobile-devices/