三只猫的温暖 和一个人的自言自语

Demo Page: jQuery on Demand

Load jQuery if it is not present

jQuery detection and loading mechanism stolen shamelessly from a CSS-Tricks article, and adapted to my own purposes.

QR tooltip on Demand

Next, try to slap my QR tooltip onto that button, and load necessary files. Click the above button first, see that jQuery isn’t loaded. Then click this button again to generate a QR code, which requires jQuery and another two plugins to work. At last click the above button again to see that jQuery is indeed loaded.

The tooltip complicates things a lot. In order for it to “just work”, so that the user will not notice anything or have to do anything besides clicking once, a number of things need to happen:

  1. Determine if jQuery is loaded;
  2. Determine if tooltipster and qrcode is loaded;
  3. Either load tooltipster and qrcode or load jQuery then tooltipster and qrcode;
  4. Additionally, tooltipster CSS has to be loaded as well;
  5. Make the QR tooltip, and stop the script from being executed again;

Here is a flowchart, made with the excellent Lucidhart:

Note that jQuery is assumed if tooltipster and qrcode is present.
Note that jQuery is assumed if tooltipster and qrcode is present.

Note there is an assumption made in this process: if tooltipster and qrcode are present, we do not check for jQuery’s presence. This is because both tooltipster and qrcode are jQuery plugins and they would not work without jQuery. So it is assumed that whenever a page preloads tooltipster and qrcode, it would load jQuery before the plugins (switch use-jquery is set to true). The dependency is not checked by the system and is the responsibility of the author (in this case, me). If somehow the plugins were loaded without jQuery preceding them, an error would be logged in the console and the contraption would not work.

So there I’ve done it. I crammed two functions into one button. When clicked for the first time, it loads necessary scripts to make a QR tooltip. Then it would alter its own onclick property, to change its function into showing the tooltip and to prevent initialize again.