I just read about the "lazy loading" design pattern.
Is it ok to overuse lazy loading to load all classes and forget about include(..)
entirely?
What are the cons of this approach?
Lazy loading is a technique used by web pages to optimize load time. With lazy loading, a web page loads only required content at first, and waits to load any remaining page content until the user needs it. Lazy loading reduces the time it takes for a web page to open because the browser only loads a fraction of the content on the page at a time.
Lazy loading is great for long web pages with lots of heavyweight content (like images, gifs, and videos) that are non-essential to the user experience on first load. There are no strict guidelines for what pages need lazy loading, but you can test your site’s performance and user engagement with and without lazy loading to make this call.
Anything resting above the fold shouldn't be lazy-loaded. Such resources should be considered critical assets, and thus should be loaded normally. Lazy-loading delays the loading of resources until after the DOM is interactive when scripts have finished loading and begin execution.
While lazy-loading images and video have positive and measurable performance benefits, it's not a task to be taken lightly. If you get it wrong, there could be unintended consequences. As such, it's important to keep the following concerns in mind.
A couple points on autoloading:
You will see a nice performance improvement by using autoloading versus always including all of your files all the time (especially as the number of files grows larger and larger).
When implementing autoloading, it is
better to use
spl_autoload_register()
than
__autoload()
.
Although a lot of times when people talk about lazy loading in PHP, they are talking about something like the following:
class Foo {
protected $bar = null;
public function getBar() {
if ($this->bar == null) {
$this->bar = ExpensiveOperation();
}
return $this->bar;
}
}
Then you only load a property when it actually needs to be used, and not every time you instantiate the object, which can potentially have some good benefits.
One benefit of a lazy loader is that it only loads the class files that are actually needed by the script during the course of its execution, potentially saving memory; when otherwise you might include all class files, whether they are needed or not. Depending on your scripts, this can make quite a difference.
It is fine to use explicit includes, or to have __autoload()
find your classes for you. Either way.
I wouldn't recommend mixing the two strategies, though. The include
lines would be unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With