Advertisement
Guest User

Untitled

a guest
Mar 20th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.   var exports = {};
  3.  
  4.   window.module = {
  5.     export: function(data) {
  6.       var _ = this;
  7.  
  8.       var exportUrl = document.currentScript.getAttributeNode('src');
  9.       var moduleHash = _.hash(exportUrl.value);
  10.  
  11.       exports[moduleHash] = data;
  12.     },
  13.     import: function(url) {
  14.       var _ = this
  15.  
  16.       var moduleHash = _.hash(url)
  17.       if (result = exports[moduleHash]) {
  18.         console.log('cache hit!')
  19.         return Promise.resolve(result)
  20.       }
  21.  
  22.       return new Promise(function(resolve, reject) {
  23.         var script = document.createElement('script');
  24.         var src = document.createAttribute('src');
  25.        
  26.         src.value = url
  27.         script.setAttributeNode(src)
  28.        
  29.         script.addEventListener('load',function() {
  30.           resolve(exports[moduleHash])
  31.         })
  32.         script.addEventListener('error', function(err) {
  33.           reject(err)
  34.         })
  35.        
  36.         document.body.appendChild(script)
  37.       })
  38.     },
  39.     hash: function(str){
  40.       var hash = 0;
  41.       if (str.length == 0) return hash;
  42.       for (i = 0; i < str.length; i++) {
  43.           char = str.charCodeAt(i);
  44.           hash = ((hash<<5)-hash)+char;
  45.           hash = hash & hash; // Convert to 32bit integer
  46.       }
  47.       return hash;
  48.     }
  49.   }
  50. })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement