Last active
December 11, 2015 06:29
-
-
Save senky/4559674 to your computer and use it in GitHub Desktop.
Along with idea of responsive design, we have discovered, that there are many accompanying problems with it's usage. One of them lays in small hardware resources hidden under the hood of mobile or other portable devices. This small object uses simple hack to make JS load whenever wanted, and parsed whenewer wanted, too. This means, you can make …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ljs = { | |
/** | |
* Loads defined script as plain text | |
*/ | |
load: function (script_name) { | |
// pretty well known, right? | |
var s = document.createElement('script'); | |
// wait! Watch this - the whole hack lays in this line. | |
// In fact, you do not need to use evil eval() to load JS before, | |
// and parse it on demand. You can load it as plain text, and | |
// add again as text/javascript (see ljs::parse()) to get it parsed. | |
// It won't load again, as it is stored in the cache already. And if | |
// it is not stored, just give it some expiration headers explicitly. | |
s.type = 'text/plain'; | |
s.id = script_name; | |
s.src = script_name; | |
document.getElementsByTagName('body')[0].appendChild(s); | |
}, | |
/** | |
* Parses script | |
*/ | |
parse: function (script_name) { | |
var s = document.createElement('script'); | |
s.type = 'text/javascript'; | |
s.src = script_name; | |
document.getElementsByTagName('body')[0].appendChild(s); | |
}, | |
/** | |
* Parses localy defined and yet commented script | |
*/ | |
parseLocal: function (script_id) { | |
// get what's inside of the element | |
var js = document.getElementById(script_id).innerHTML; | |
// remove comments | |
js = js.replace(/[\n\r\s\t]+\/\*/, ''); // opening tag /* | |
js = js.replace(/(.*)\*\/([\n\r\s\t]+)?/, ''); // closing tag */ | |
// eval is evil, but... | |
eval(js); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment