Get The Best PageSpeed Score
For Your WordPress Website
With the help of a laravel image optimizer, you can speed up your website by optimizing the image file.
Adding images is essential to making your website more aesthetically pleasing. However, adding too many unoptimized images can slow down your website’s loading time. According to LoadNinja, images account for 64% of the overall page’s size, which can severely impact the loading speed of your Laravel website.
Way too many website owners struggle with the slow loading speed of their Laravel websites due to the rampant use of unoptimized images.
Chances are you are using similar issues too. Here we will discuss how to manually optimize images on the Laravel website using an image optimizer & we would also see how you can do it yourself using your coding skills without an image optimizer.
However, manually optimizing an image can be challenging if you are not from a technical background.
A Laravel image optimizer can make this process easier. There are several Laravel image optimizers available online that can help you optimize images on your website. However, investing time in the wrong laravel image optimizer can waste your valuable as well as money.
Hence, before investing in a laravel image optimizer, first, you need to know the effectiveness of the laravel image optimizer.
Here, we will explore, as a Laravel image optimizer, how RabbitLoader optimizes your images on the Laravel website and helps you speed up the website.
But before diving into the solution, first, we will talk about the importance of image optimization, the most common reason behind a slow laravel website and mention a few freely available tools to measure your laravel website’s performance.
When it comes to a website’s PageSpeed optimization, the first thing that pops up in almost every website owner’s mind is “image optimization.” Now, you may wonder if this is really fruitful for optimizing Laravel performance.
Get The Best PageSpeed Score
For Your WordPress Website
Let’s explain the importance of image optimization, which includes:
The total page file size indicates the summation of each resource file’s size of a webpage, such as HTML, CSS, JavaScript files and media (image, video, and map) files. Among the resource files, images consume the most space and thus are mostly responsible for increasing the page loading time.
Optimizing images can significantly improve the page loading time by reducing the total page file size of a website. Image optimization is more effective if your website has a lot of images.
Let’s understand with an example.
Assume a particular page on your website has 10 images of 500kb each. The total image file size will be 5 MB, increasing the webpage’s page load time. By optimizing the images, you can reduce the image file size, which can reduce the total page file size. Hence, the website’s page loading performance would be improved greatly.
A website’s loading creates the first impression of your website in the user’s mind. An unoptimized image can typically increase the page loading time of a Laravel website, which can negatively affect the user experience and increase the bounce rate, harming the conversion rate. According to the envisage digital website, a one-second delay in the page loading time can reduce the conversion rate by 7%.
By optimizing the image of the website, you can improve its page loading performance, which would in turn would enhance the user experience. Users are more likely to engage with your Laravel website’s content, increasing the on-page time and reducing the bounce rate. Hence, you may reach your goal by achieving a good conversion rate.
Another key benefit of image optimization is making your website more mobile-friendly. This is essential to ensuring the business’s consistent conversion rate and good ranking in any search engine.
According to Think with Google, if the page loading time is increased by 10 seconds from 1 second, the bounce rate will be increased by 123% for the mobile version of the website.
By optimizing images, you can make your Laravel-based website more mobile-friendly and provide a better user experience to your mobile users.
If you know the reason behind a slow Laravel website, you can plan your efforts to optimize the loading speed of your website. Here, we will discuss the most common reasons behind a slow Laravel website, which includes the following:
As mentioned earlier, using too many unoptimized images can increase the total page file size of a Laravel website, which can slow down the page loading time of that website.
Images that are not present above the fold are also known as non-critical images. These non-critical images do not need to load during the initial page load.
Get The Best PageSpeed Score
For Your WordPress Website
Hence, if you do not defer them, your website’s page loading time can increase. Below, in this blog post, we have discussed how you can defer the non-critical images.
A CDN cache reduces the network latency caused by the long physical distance between the user and the origin server. If you are not using CDN cache, then the resource file will be directly retrieved from the origin server.
If the distance between the server and the user is high, then it will take more time to load the resource file. This can slow down the page loading time of a Laravel website.
If you are curious about your website’s performance, here are freely available tools to measure it.
When it comes to measuring the PageSpeed performance of any website, the first tool that comes to mind is Google PageSpeed Insights(PSI). Google developed this PageSpeed analyze tool to measure the website’s performance based on both lab data as well as field data.
Google PageSpeed Insights scores webpages on a scale of 0 to 100 based on the Core Web Vitals metrics (a set of performance metrics developed by Google). It also provides suggestions on how to improve PageSpeed performance.
Just enter our domain name on Google PSI and click on “Analyze” to see your home page’s PageSpeed score. Along with the PageSpeed score, you can also see the Core Web Vitals Assessment results.
For better understanding, Google also categorizes the PageSpeed score based on threshold values. If your Laravel website’s PageSpeed score is 90 or above, then the website’s PageSpeed performance is good; no further optimization is needed.
However, if the PageSpeed performance score is more than 50 but doesn’t exceed 90, then it needs to be improved to be in a green zone. A below-50 PageSpeed score of your website indicates that the website fails the test in Google PageSpeed Insights.
GTMetrix is the best alternative to Google PageSpeed Insights for monitoring a website’s PageSpeed performance. This online PageSpeed monitoring tool allows you to customize your PageSpeed test by choosing the location, network and browser type.
GTmetrix grades your website’s PageSpeed performance on a scale of A to F. You can also see the core web vitals performance here. In the premium version of GTmetrix, you can see the PageSpeed performance of each page of your Laravel website.
Optimizing images can improve the website’s PageSpeed performance. But how do we optimize images?
Optimizing images manually involves a multitude of technicalities, which can be daunting for a non-technical person. However, with the help of a laravel image optimizer like RabbitLoader SDK, you can easily optimize the images in Laravel. We will discuss this in the next section.
Here, we will mainly concentrate on how to optimize images on the Laravel website manually.
Image compression reduces the size of an image file. There are two types of image compression methods: lossy compression and lossless compression.
While lossy compression slightly reduces the visual quality of the image, lossless compression reduces the image file size without losing the image quality. Image compression is one of the most effective image optimization techniques.
Let’s discuss how to do image compression on your Laravel website.
composer create-project –prefer-dist laravel/laravel image-compress-project
composer requires spatie/image-optimizer
Here we are using spatie/image-optimizer Image compression package. If you want to use another package, just change the package name in the above syntax.
sudo apt-get install jpegoptim
sudo apt-get install pngquant
sudo apt-get install optipng
sudo npm install -g [email protected]
sudo apt-get install gifsicle
sudo apt-get install webp
brew install jpegoptim
brew install pngquant
brew install optipng
npm install -g [email protected]
brew install gifsicle
brew install webp
php artisan make: controller Compress_Controller
Compress_Controller is the class. You can modify the class name.
use Exception;
Illuminate\Http\Request;
Illuminate\Support\Facades\Validator;
Spatie\ImageOptimizer\OptimizerChainFactory;
//Extend the controller class
class Compress_Controller extends Controller
{
public function index()
{
// entry point of the program which shows the image optimizer view
return view(‘image-optimizer’);
}
public function compress(Request $request)
{
// Check the image formats and upload size(Here, we will provide the max size Max upto 5MB….. You can can the max size according your needs)
$validator = Validator::make(
$request->all(),
[
'image' => 'required|file|mimes: jpeg,jpg,png,gif,svg,webp|max:5120',
]
);
if($validator->fails()){
return redirect()->back()->withErrors($validator->errors())->withInput();
}
try{
// Get the uploaded image from the request
$image = $request->file('image');
// Make a unique filename for the uploaded image
$imagename = time().'.'.$image->getClientOriginalExtension();
// Set the path to save the original image
$imagepath = public_path('/images/');
// Set the path to save the compressed image
$pathToOutput = public_path('/optimizedImage/');
// Save the original image
$image->move($imagepath, $imagename);
// Compress the image and save it to the optimizedImage path using Spatie's OptimizerChainFactory
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($imagepath.$imagename,$pathToOutput.$imagename);
// Delete the original image
unlink($imagepath.$imagename);
// Redirect back to the image uploader with the success message.
return back()->with('success', 'successfully compressed the image.');
}
catch(Exception $e)
{
// Redirect back to the image uploader with an error message.
$error = 'Opps! something goes wrong. Please try later’;
return redirect()->back()->with('error',$error)->withInput();
}
}
}
<div class="container" style="margin-top: 50px;">
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<h2>Compress JPEG</h2>
<form action="{{ url('compress') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group">
<input type="file" name="image" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Compress</button>
</form>
</div>
Route::get(‘/image-optimizer’, [ImageController::class, ‘index’]);
Route::post(‘/compress’, [ImageController::class, ‘compress’]);
php artisan serve
Without implementing lazy loading, improving PageSpeed performance can be difficult for a website, especially when it has many images. In general, the browser loads each image during the page rendering, which can make the loading time longer.
Implementing lazy loading can improve page loading time by instructing the browser to load only images that are visible in the above-the-fold. Let’s see how to implement lazy loading on the Laravel website.
Here we will explain this step by step to make the process easier.
composer requires intervention/image
‘InterventionImage’ => Intervention\Image\Facades\Image::class,
$table->string(‘image’);
<form action="/upload" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
use Intervention\Image\Facades\Image;
public function upload(Request $request)
{
$image_Path = $request->file('image')->store('images');
//Save the image path to the database using your model
YourModel::create([
'image' => $image_Path,
]);
return redirect()->back();
}
<img src="{{ asset('path-to-placeholder-image') }}" data-src="{{ asset($model->image) }}" alt="" loading="lazy">
<script src="{{ mix('js/app.js') }}"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
const lazyImages = document.querySelectorAll('img[loading="lazy"]');
const imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
const lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.onload = function() {
lazyImage.removeAttribute("data-src");
lazyImage.removeAttribute("loading");
};
observer.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
imageObserver.observe(lazyImage);
});
});
</script>
Please keep in mind that you need to replace the path-to-placeholder-image according to your image files requirement.
As discussed earlier, using a CDN can reduce the network latency between the user and the server, which can improve the loading time of your website. Now, you may be worried about how to implement a Content Delivery Network (CDN) on the Laravel website.
Get The Best PageSpeed Score
For Your WordPress Website
Like previous image optimization strategies, you can easily implement the Content Delivery Network in your Laravel website by following the below steps. Here we are using CDNsun.
<?php
return [
...
'cdn_enabled' => true,
/* Here we are using CDNsun. You need to modify the cdn_domain if you are using other CDN*/
'cdn_domain' => '12345.r.cdnsun.net',
'cdn_protocol' => 'https',
];
<?php
function cdn($url = null)
{
$url = (string) $url;
if(empty($url))
{
throw new Exception('URL missing');
}
$pattern = '|^http[s]{0,1}://|i';
if(preg_match($pattern, $url))
{
throw new Exception('Invalid URL. ' .
'Use: /image.jpeg instead of full URI: ' .
'https://domain.com/image.jpeg.'
);
}
$pattern = '|^/|';
if(!preg_match($pattern, $url))
{
$url = '/' . $url;
}
if(!Config::get('app.cdn_enabled'))
{
return $url;
}
else
{
return Config::get('app.cdn_protocol') . '://' . Config::get('app.cdn_domain') . $url;
}
}
"autoload": {
...
"files": [
"app/helpers.php"
]
},
Step 4: Finally, you need to add a CDN helper.
{{ cdn('/image.jpg') }}
Note: Before modifying anything in the resource file, first back up all your resource files.
You have already seen that optimizing images manually can be daunting due to its extensive technicalities. Most website owners invest a lot of money in the development team or ten different Laravel image optimizers, which may ruin the website’s PageSpeed performance by conflicting with each other.
Here, RabbitLoader will provide you with a superior solution. Let’s see how RabbitLoader optimizes the images as a Laravel image optimizer.
Not only as a laravel image optimizer, but you can also use RabbitLoader for Laravel performance optimization, such as minifying and compressing the resource files (HTML, CSS, and JavaScript), generating critical CSS, reducing unused CSS & JavaScript and many more. For more details, check our RabbitLoader speed-up laravel website.
Thus, if you are also looking for a laravel image optimizer, don’t invest your money in the wrong laravel image optimizer. Install RabbitLoader to optimize all images and improve Laravel performance. Go through our knowledge base for installation guidance.
Get The Best PageSpeed Score
For Your WordPress Website