rgrove / lazyload

:skull: An ancient tiny JS and CSS loader from the days before everyone had written one. Unmaintained.
MIT License
1.39k stars 288 forks source link

Don't import the same resource multiple times #5

Closed guiocavalcanti closed 13 years ago

guiocavalcanti commented 13 years ago

Hello,

I'm using the pushstate API to reload just one subtree of the DOM on each request while maintaining the <head> element untouched. Some pages of my site need some extra JS or CSS which I'm going to load also using lazyload. Since the user may visit the same page multiple times, the same resource is being included in the <head> over and over.

How should I detect if some resource is already present and, if it is, prevent LazyLoad o include the file?

rgrove commented 13 years ago

At some point I'll probably add a simple URL-based lookup hash to LazyLoad so that it can at least avoid loading URLs it's already seen. I don't want to implement anything more complex than that, though; it would increase the code size too much.

In the meantime, you could write a thin wrapper function around LazyLoad that uses a lookup hash just like I've described, and avoids loading anything that's already been loaded.

guiocavalcanti commented 13 years ago

Ok, I'll try that. Thanks for the fast answer.

kamov commented 10 years ago

Hi can someone show me an example?

I am trying to do this, but is not working.

After

for (i = 0, len = pendingUrls.length; i < len; ++i) {
      url = pendingUrls[i];

I added this code:

                                var all_scripts = document.getElementsByTagName("script");

                                for(var i = 0; i < all_scripts.length; i++) {

                                    if(all_scripts[i].src ==url) {
                                        alert('I found you!! Dont load me');
                                        return true; // continue to next
                                    }
                                }
                                alert('I am going to load you.' + url);
kamov commented 10 years ago

solved in this way (I appreciate any suggestion for improve it):

I just change the for loop which appendChild nodes to head, by checking if that src it's already on head.

The final code is:


    var all_scripts = document.getElementsByTagName("script");
    var i_found_you = false;

    for (i = 0, len = nodes.length; i < len; ++i) {

      for(var ii = 0; ii < all_scripts.length; ii++) {

          if(all_scripts[ii].src == nodes[i].getAttribute('src')) {

              i_found_you = true;
              break; // continue to next
          }
      }

      if(!i_found_you)
        head.appendChild(nodes[i]);

    }
kamov commented 10 years ago

not working :(