Reputation: 107
In the process of trying to mimic sites like Youtube, and loading only the specific fragments of a page on link click, I have tried making a function that loads/unloads the specific JS files and CSS files needed for the current page.
I've noticed that when CSS files get removed from the DOM, the styling from that file is no longer vaild, and only gets valid again if I add the specific link
tag again. However, it seems like JS files get stored in the memory when loaded, and simply removing the reference in the DOM doesn't prevent the functions associated with that file to still work. How does Youtube go around this problem, or do you have your own suggestions on which path I should go to achieve unloading/loading JS files "completely"?
One idea I had was to just have all variables, element IDs etc in my code (both when it comes to HTML and JS) to be unique, and have an array that keeps check of which JS files have been loaded - so that there won't be more than one of each JS file in memory. But I guess that's not a safe solution, since the GC can remove a JS file from memory if that "page" hasn't been used for long?
Upvotes: 2
Views: 900
Reputation: 21769
you can set to null a variable and then the garbage collector will clean it from the memory, with this, you could load your javascript dynamically into a variable so that later you will be able to set it to null. your files could have an object or be a constructor function.
this is just a basic explanation, however, my suggestion is that you check out angularjs, reactjs and many other frameworks that suit good for developing single page applications.
if you have something already developed, requierejs is a library for dinamically load dependencies and the implementation is really straightforward and easy.
caching is another story, you can avoid/refresh cache by the way you load your files. you can add a query parameter to the url with e.g a timestamp. that way the url of the file will be different each time, and the browser will not load it from the cache. You can also use headers in order to tell the browser when the file should be refreshed from the cache, or even prevent it from caching it at all.
Upvotes: 2