kubetail-org / loadjs

A tiny async loader / dependency manager for modern browsers (899 bytes)
MIT License
2.57k stars 149 forks source link

Idempotent request option #95

Open amorey opened 5 years ago

amorey commented 5 years ago

From @BicanMarianValeriu:

Would not be useful to add a method for adding scripts loaded by other apps to cache ? Eg: I have a list of scripts id's loaded by WordPress and instead of lazyloading the same id again, I would put that list to cache and run code directly.

I was trying to make a feature request. I'm thinking that is more useful to have that method and also, eg, if script is already loaded by something else (and or plugin), do not throw the error, skip the head appending and actually run the callback instead. Throwing error breaks the js while with the solution above will continue working in case you double load the same script url/id. Makes sense ?

https://github.com/muicss/loadjs/pull/94

amorey commented 5 years ago

Here are two loading scenarios:

  1. Use browser cache to avoid multiple fetches If the expires header is set properly then subsequent calls to loadjs will trigger code execution and callback execution but not multiple fetches:

    loadjs('/file.js', function() { /* callback1 */ });  // fetch over network
    loadjs('/file.js', function() { /* callbcak2 */ }); // fetch from cache
  2. Use .ready() to fetch once and execute callbacks multiple times

    loadjs('/file.js', 'file-load');
    
    loadjs.ready('file-load', function() { /* callback1 */ });
    loadjs.ready('file-load', function() { /* callback2 */ });

Does your use case fit under one of these?

BicanMarianValeriu commented 4 years ago

Sorry for late answer. 3. File is loaded by some other application/method and not via this plugin. Eg, I have an array with this files ids. For each ID I need a way of pushing them to cache then:

loadjs('file.js', 'file-id', ()=> { console.log('File is identified as loaded by it's id and instead of doing nothing/throwing error just run the callback function ); });

That's is why I was thinking about a method of specifying cache before any loadjs function run.

amorey commented 4 years ago

Unfortunately, if the file is being loaded outside of LoadJS then it's going to be difficult to detect whether or not it has already been fetched/loaded. I'm not sure it's even possible to detect all file downloads triggered by other code.

BicanMarianValeriu commented 4 years ago

Agree with you but my Idea was to "tell" this plugin that x,y,z files have been loaded by some other code and plugin "can" safely run the callback instead of throwing error. Nothing fancy, just need this since you know plugins code better - maybe a method similar to 'isDefined' ... loadJs.preloadCache( [file-id-1, file-id-2, ...] );

amorey commented 4 years ago

Why do you need LoadJS for this? Why not just run the callback after the files have been loaded?