Skip to content

Update/add #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 106 additions & 88 deletions cached-webpgr.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
*
* usage example:
* ```
* requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
* requireScript('examplejs', '0.0.3', 'example.js');
* requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', false, function(){
* requireScript('examplecss', '0.0.3', 'example.css',true);
* });
* ```
*/
Expand All @@ -19,95 +19,113 @@
* It will make an ajax call to retrive the desired script from the provided url and store it
* in the localStorage under the provided name. The stored script will be wrapped like in this example:
* `{content: '// scrip content $(document).ready(...)', version: '1.02.03'}`
* @param {string} name localStorage identifier; shoud be the same as on the server-side
* @param {string} url `path/to/script.js`; shoud be on the same server (or with remove with CORS header access-control-allow-origin:*)
* @param {string} url (see `requireScript` or 'css')
* @param {string} name (see `requireScript` or 'css')
* @param {string} version (see `requireScript` or 'css')
* @param {Boolean} css (false =js, true=css)
Copy link
Owner

@select select Nov 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a string would be better here so the API is clearer so I would change this to type: ['css' || 'js], or we parse the url suffix, which should be even better since the API would not change.

var extension = url.split('.').pop()
if (extension === 'js') ...
if (extension === 'css') ...

or you could even do

var css = url.split('.').pop() === 'css'

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • German
    habe mal "cached-webpgr" zerlegt und zu einer version 2 überarbeitet!
    js und css werden unterstütz!
    vielleicht ist die Ideen/Überarbeitung Ansatz interessant für dich.
  • English translation by google
    I disassembled "cached webpgr" and belonged to version 2!
    js and css are processed!
    Perhaps the ideas / revision approach is interesting for you.

cached-webpgr-alpha-v2

* @param {Function} callback (see `requireScript` or 'css')
*/
function _cacheScript(name, version, url) {
var xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
localStorage.setItem(name, JSON.stringify({
content: xmlhttp.responseText,
version: version
}));
} else {
console.warn('error loading '+url);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
/**
var dd=document;
function _cacheScript(name, version, url, css, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
localStorage.setItem(name, JSON.stringify({
content: xmlhttp.responseText,
version: version
}));
_injectScript(name, version, url, css, callback)
} else {
if (callback) callback();
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
/*
* ##_loadScript
* For loading external scripts (local or cross domain with CORS)
* @param {string} url (see `requireScript`)
* @param {string} name (see `requireScript`)
* @param {string} version (see `requireScript`)
* @param {Function} callback (see `requireScript`)
* @param {string} url (see `requireScript` or 'css')
* @param {string} name (see `requireScript` or 'css')
* @param {string} version (see `requireScript` or 'css')
* @param {bool} css (false =js, true=css)
* @param {Function} callback (see `requireScript` or 'css')
*/
function _loadScript(url, name, version, callback) {
var s = document.createElement('script');
function _loadScript(name, version, url, css, callback) {
var s
if (css)
s = dd.createElement('script');
else
s = dd.createElement('style');

if (s.readyState) {
s.onreadystatechange = function()
{
console.log("s.onreadystatechange");
if (s.readyState == "loaded" || s.readyState == "complete") {
s.onreadystatechange = null;
if (callback) callback();
}
};
} else {
console.log("s.onload");
s.onload = function() {
if (callback) callback();
}
}
s.setAttribute("src", url);
dd.getElementsByTagName("head")[0].appendChild(s)
}

if (s.readyState) { //IE
s.onreadystatechange = function() {
if (s.readyState == "loaded" || s.readyState == "complete") {
s.onreadystatechange = null;
_cacheScript(name, version, url);
if (callback) callback();
}
};
} else { //Others
s.onload = function() {
_cacheScript(name, version, url);
if (callback) callback();
};
}

s.setAttribute("src", url);
document.getElementsByTagName("head")[0].appendChild(s)
}

/**
* ##_injectScript
* Injects a script loaded from localStorage into the DOM.
* If the script version is differnt than the requested one, the localStorage key is cleared and a new version will be loaded next time.
* @param {object} content wrapped serialized code `{content: '// scrip content $(document).ready(...)', version: '1.02.03'}`
* @param {string} name (see `requireScript`)
* @param {string} version (see `requireScript`)
* @param {Function} callback (see `requireScript`)
*/
function _injectScript(content, url, name, version, callback) {
var c = JSON.parse(content);
// cached version is not the request version, clear the cache, this will trigger a reload next time
if (c.version != version) {
localStorage.removeItem(name);
_loadScript(url, name, version, callback);
return;
}
var s = document.createElement('script');
s.type = "text/javascript";
var scriptContent = document.createTextNode(c.content);
s.appendChild(scriptContent);
document.getElementsByTagName("head")[0].appendChild(s);
if (callback) callback();
}
/*
* ##_injectScript
* Injects a script loaded from localStorage into the DOM.
* If the script version is differnt than the requested one, the localStorage key is cleared and a new version will be loaded next time.
* @param {string} url (see `requireScript` or 'css')
* @param {string} name (see `requireScript` or 'css')
* @param {string} version (see `requireScript` or 'css')
* @param {bool} css (false =js, true=css)
* @param {Function} callback (see `requireScript` or 'css')
*/
function _injectScript(name, version, url, css, callback) {
var c = JSON.parse(localStorage.getItem(name));
if (c.version != version) {
localStorage.removeItem(name);
_cacheScript(name, version, url, css, callback);
return;
}
var s
if (css)
s = dd.createElement('style');
else
s = dd.createElement('script');

var scriptContent = dd.createTextNode(c.content);
s.appendChild(scriptContent);
dd.getElementsByTagName("head")[0].appendChild(s);
if (callback) callback();
}

/**
* ##requireScript
* If the requested script is not available in the localStorage it will be loaded from the provided url (see `_loadScript`).
* If the script is present in the localStorage it will be injected (see `_injectScript`) into the DOM.
* @param {string} name identifier of the script in the local cache
* @param {string} version version string that is used to check if the script needs to be updated
* @param {string} url `path/to/script.js` that should be caced; can be local (or cross domain with CORS header allowing cross domain access)
* @param {Function} callback function that is extecuted once the script is loaded
*/
function requireScript(name, version, url, callback) {
var c = localStorage.getItem(name);
if (c == null) {
_loadScript(url, name, version, callback);
} else {
_injectScript(c, url, name, version, callback);
}
}
/*
* ##requireScript
* If the requested script is not available in the localStorage it will be loaded from the provided url (see `_loadScript`).
* If the script is present in the localStorage it will be injected (see `_injectScript`) into the DOM.
* @param {string} url (see `requireScript` or 'css')
* @param {string} name (see `requireScript` or 'css')
* @param {string} version (see `requireScript` or 'css')
* @param {bool} css (false =js, true=css)
* @param {Function} callback (see `requireScript` or 'css')
*/
function requireScript(name, version, url, css, callback) {
if (typeof localStorage === 'undefined')
{
console.log("localStorage");
_loadScript(name, version, url, css, callback)
}else if (localStorage.getItem(name) == null) {
_cacheScript(name, version, url, css, callback);
} else {
_injectScript(name, version, url, css, callback);
}
}
2 changes: 1 addition & 1 deletion cached-webpgr.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
* License: MIT
*/

function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};

var dd=document;function _cacheScript(e,t,a,n,o){var c=new XMLHttpRequest;c.onreadystatechange=function(){4==c.readyState&&(200==c.status?(localStorage.setItem(e,JSON.stringify({content:c.responseText,version:t})),_injectScript(e,t,a,n,o)):o&&o())},c.open("GET",a,!0),c.send()}function _loadScript(e,t,a,n,o){var c=n?dd.createElement("script"):dd.createElement("style");c.readyState?c.onreadystatechange=function(){console.log("s.onreadystatechange"),"loaded"!=c.readyState&&"complete"!=c.readyState||(c.onreadystatechange=null,o&&o())}:(console.log("s.onload"),c.onload=function(){o&&o()}),c.setAttribute("src",a),dd.getElementsByTagName("head")[0].appendChild(c)}function _injectScript(e,t,a,n,o){var c,r=JSON.parse(localStorage.getItem(e));if(r.version!=t)return localStorage.removeItem(e),void _cacheScript(e,t,a,n,o);c=n?dd.createElement("style"):dd.createElement("script");var d=dd.createTextNode(r.content);c.appendChild(d),dd.getElementsByTagName("head")[0].appendChild(c),o&&o()}function requireScript(e,t,a,n,o){"undefined"==typeof localStorage?(console.log("localStorage"),_loadScript(e,t,a,n,o)):(null==localStorage.getItem(e)?_cacheScript:_injectScript)(e,t,a,n,o)}
// ---

requireScript('jquery', '1.11.5', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
Expand Down Expand Up @@ -47,4 +46,4 @@ <h1>localStorage Script Caching Demo</h1>
</sub>
</p>
</body>
</html>
</html>