This blog uses github as image hosting service after migration. However, sometimes the image loading speed is slow. After some investigation, we found that we can easily improve the image loading speed by jsdelivr CDN.

# Jsdelivr Image Url Format

Assume the original github image url is:

https://raw.githubusercontent.com/{user}/{repo}/master/{folderpath}/{filename}

To leverage jsdelivr CDN, just convert the url to this:

https://cdn.jsdelivr.net/gh/{user}/{repo}/{folderpath}/{filename}

Or just do a prefix replacement:

https://raw.githubusercontent.com/{user}/{repo}/master/

-->

https://cdn.jsdelivr.net/gh/{user}/{repo}/

For example, for image p.png in github user user's repository repo, folder a/:

https://raw.githubusercontent.com/user/repo/master/a/p.png

The CDN url should be:

https://cdn.jsdelivr.net/gh/user/repo/a/p.png

If you encounter the following error:

Package size exceeded the configured limit of 50 MB. Try https://github.com/user/repo/tree/master/master/a/xxx.jpg instead.

Probably the image url is wrong. For this case, there is a duplicate master and the url should be: https://cdn.jsdelivr.net/gh/user/repo/a/xxx.jpg

# Script to Replace Image Url

Use the following script to replace the image url:

#!/bin/bash

for f in ./source/_posts/*.md; do
echo "Process "$f sed -i 's/https:\/\/raw.githubusercontent.com\/user\/repo\/master\//https:\/\/cdn.jsdelivr.net\/gh\/user\/repo\//'$f
done

# Reference

https://blog.csdn.net/q906270629/article/details/115394248

https://zhuanlan.zhihu.com/p/76951130