They are powerful, but sometimes the gain outweighs the gain. If you are using jQuery, there is a built-in method for loading a single js file. You can use this method when you need to delay loading some js plug-ins or other types of files. Here’s how to use it!
1. The jQuery getScript() method loads JavaScript
jQuery has a built-in method to load a single js file; when the loading is completed, you can perform subsequent operations in the callback function. The most basic way to use jQuery.getScript is as follows:
/*
Do some things that need to be executed after loading is completed
*/
});
The most common use of jQuery.getScript is to lazy load a js plugin and execute it when loading is complete:
2. Caching problem
There is a very important issue. When using jQuery.getScript, you need to use a timestamp string following the js address that needs to be loaded to prevent it from being cached. However, if you want this script to be cached, you need to set the global cache variable, like this: