User:SD0001/Making user scripts load faster

User scripts can be made to load faster with the help of caching. However, this is experimental, let me know if you face any issues on the talk page.

Add the following snippet of minified code to the top of your page:

If you don't like this ugly blob of incomprehensible code, you can instead add the fully and pretty version (but this takes up a lot of lines):

(The two code snippets are functionally the very same).

Note that the code block necessarily needs to be at the top of your common.js page for it to take effect.

It replaces the existing implementations of,  ,   and. No changes are needed in the way you normally add new user scripts.

Impact
The effect can be seen by keeping the network tab of your browser dev tools open and navigating through different pages. (Don't reload the same page – that's seen as a hard reload in some browsers and causes bypassing of cache.) Also ensure you have the "Disable cache" option unchecked in the devtools. In Chrome, you should see that most script fetches are resolved by the disk cache itself which is very fast.



Caveats

 * The snippet above makes all scripts and stylesheets cached by your browser for up to one day (86400 seconds). If any of the scripts are updated, it may take you up to 1 day to see the updates. Doing a hard reload will clear the caches. On Google Chrome, just hitting the "reload" button on any page causes a hard reload. On other browsers, you may need to use.

Technical details
loadResource function:


 * The API is used instead of index.php because requests to the latter never appear to be cached for logged-in users. With the API's caching parameters, responses get the Cache-Control header  while the one set by index.php is.
 * The  attribute enables public caching in Varnish, etc. See T97096. However, no public caching takes place for requests by users with ability to view revision-deleted or suppressed content (ref: ).
 * The  causes the API to set the   header to avoid CORS issue while loading cross-wiki scripts.
 * The contentmodel of the page is checked before the js/css code is evaluated. Non-javascript contentmodel pages won't be evaluated as JS, consistent with a call to index.php for non-JS page with ctype=text/javascript failing with a 403 error.
 * Using mw.loader.getScript to load a missing page gives a resolved promise. This is consistent with index.php call to load JS from a non-existent page with a protected title (i.e, a userspace title ending with ".js" or a mediawiki namespace title) giving a 200 response.
 * However, using index.php to load JS from a non-existent page but with non-protected title gives a 403. loadResource will give a resolved promise instead.