Re-executing JavaScript files - javascript

I asked this sort of question before ( Application fails to dynamically _re_load JavaScript files ) but I couldn't quite resolve the problem (if it has any solution), so I will put this in another fashion, a simpler one:
Can one unload a file from the browser's memory for posterior reloading?
(Removing the tag is not enough apparently.)
Or more relevant, if a reinsert the tag after removing it, is that code rerun (apparently not)?
How can accomplish the latter?
Thanks in advance.

You could generate a random number and then attach it to the end of the filename like this: .../script.js?r=0.25300762383267283. Then the browser would think it's a new file and not reference it from the cache.

I don't think it is possible to unload a script file.
As to the re-run issue, you could try giving each instance you call a JS file a varying GET parameter (e.g. the current timestamp). That might / should cause the browser to re-execute the file.
What are you trying to achieve? There may be smarter ways than re-loading a script file.

Related

What's the ultimate and definitive way to clear the browser cache?

I'm using Liferay CMS as part of my Uni course in full stack development and, as a final project, I have to use the d3.js library to display some graphs. I'm struggling to clear the browser cache though, and that makes the developing process very tedious and time consuming: I'd like to see my front-end changes right away without having to fiddle with the browser cache, especially because, as I'm working with svg elements, it sometimes gets tricky to line up stuff and so on. Sometimes clearing the cache works, sometimes it doesn't, as well as opening a new private window, but there must be a conclusive and foolproof method to delete all cached elements. Does somebody know how to do that?
Liferay has a "Developer Mode" which should bypass quite a lot of caching anyway. In your portal-ext.properties (typically in ${liferay.home}, just add the line
include-and-override=portal-developer.properties
to activate this mode.
It will also skip minifiers and concatenation of all of the different resources that you're loading.
This doesn't clear caches but will solve your updating problem.
In the HTML, add an (unused) query string to the html link to linked files and alter it each time you make an update to the file. e.g. for css:
<link rel="stylesheet" href="styles.css?a">
Then, each time you make changes to the file pointed to, change the 'a' to 'b' or anything (Don't change the linked file's name, the query string will be ignored).
This forces the browser to 'change' the linked file each time the href changes and so the altered file gets reloaded.
The method will work for script and other linked files. The query string could be something meaningful such as version numbers - ?v1, but anything will do.
Edit, as noted by #GerardoFurtado, a further discussion of this idea is available here Cache busting via params

forbid javascript in html file

Following problem:
I've given a file with HTML inside but also maybe some script code.
Now I want to edit the file so that no script gets executed when opening the file with a browser.
My question is: What do I have to do?
Which possibilities are there to place a script inside HTML to let it get executed? I know there is the script tag, you could also do it with an iframe but what else is possible?
I definitely want to prevent any kind of script execution. How can I achieve this?
Have a look at an established, well tested HTML filter library such as http://htmlpurifier.org/ which uses a whitelist to filter possibly malicious code. Don't rely on the filtered HTML documents being secure from any javascript though, time and time again browsers are updated and new ways to sneak in javascript are discovered.

Force a script refresh using the "yepnope" JavaScript script loader

Using yepnope.js. I need to "refresh" the script, but yepnope prevents files with the same url from being re-loaded.
In the documentation, they suggest using a plugin to allow files to refresh. Is there such a plugin available? What are my other options for refreshing a script during runtime in Javascript?
I tried appending a random number as a query argument to the url. That worked, but made it much more difficult to set breakpoints while debugging, so I'd rather not do this.
Any suggestions? Thanks!
IMHO it is not possible do that using any yepnope method.
I think you only has two possibilities:
Adding a random parameter to the querystring (your current solution)
Changing the yepnope script to:
expose the scriptCache yepnope var
reset the scriptCache[url]
and finally remove the created DOM img node that has your url as src.
In addition set the cache headers to expired, to prevent browser cache.
good luck

Page-level execution of JavaScript when serving concatenated files

Scenario:
A web site with x number of pages is being served with a single, concatenated JavaScript file. Some of the individual JavaScript files pertain to a page, others to plugins/extensions etc.
When a page is served, the entire set of JavaScript is executed (as execution is performed when loaded). Unfortunately, only a sub-section of the JavaScript pertains directly to the page. The rest is relevant to other pages on the site, and may have potential side-effects on the current page if written poorly.
Question:
What is the best strategy to only execute JavaScript that relates directly to the page, while maintaining a single concatenated file?
Current solution that doesn't feel right:
JavaScript related to a specific page is wrapped in a "namespaced" init function for that page. Each page is rendered with an inline script calling the init function for that page. It works hunky-dory, but I would rather not have any inline scripts.
Does anyone have any clever suggestions? Should I just use an inline script and be done with it? I'm surprised this isn't more of an issue for most developers out there.
Just use an inline script. If it's one or two lines to initialize the JavaScript you need that's fine. It's actually a good design practice because then it allows re-use of your JavaScript across multiple pages.
The advantages of a single (or at least few) concatenated js files are clear (less connections in the page mean lower loading time, you can minify it all at once, ...).
We use such a solution, but: we allow different pages to get different set of concatenated files - though I'm sure there exists different patterns.
In our case we have split javascript files in a few groups by functionality; each page can specify which ones they need. The framework will then deliver the concatenated file with consistent naming and versioning, so that caching works very well on the browser level.
We use django and a home-baked solution - but that's just because we started already a few years ago, when only django-compress was available, and django compress isn't available any more. The django-pipeline successor seems good, but you can find alternatives on djangopackages/asset-managers.
On different frameworks of course you'll find some equivalent packages. Without a framework, this solution is probably unachievable ;-)
By the way, using these patterns you can also compress your js files (statically, or even dynamically if you have a good caching policy)
I don't think your solution is that bad although it is a good thing that you distrust inline scripts. But you have to find out on what page you are somehow so calling the appropriate init function on each page makes sense. You can also call the init function based on some other factors:
The page URL
The page title
A class set in the document body
A parameter appended to your script URL and parsed by the global document ready function.
I simply call a bunch of init functions when the document is ready. Each checks to see if it's needed on the page, if not, simply RETURN.
You could do something as simple as:
var locationPath = window.location.pathname;
var locationPage = locationPath.substring(locationPath.lastIndexOf('/') + 1);
switch(locationPage) {
case 'index.html':
// do stuff
break;
case 'contact.html':
// do stuff
break;
}
I'm really confused exactly why it doesn't feel right to call javascript from the page? There is a connection between the page and the javascript, and making that explicit should make your code easier to understand, debug, and more organized. I'm sure you could try and use some auto wiring convention but I don't think it really would help you solve the problem. Just call the name spaced function from your page and be done with it..

JavaScript Function Loading

I have a relatively large (in terms of memory use and code size) JS function (running in IE/FF) that I use only occassionally (like, a couple of times per day). I think I can get rid of it when I'm done with it by nulling out its function (using the variable name of the 'function object', as it were).
I am fuzzy though on how I would get it back, supposing maybe some time later I wanted to do it again. How would I load JS on the fly from a URL like the 'script' tag does?
Does this whole line of reasoning make sense?
It's a tad hacky, but there are two ways:
Use DOM methods to insert a script tag into the page to a file that has that function in it. You might need to add a query string so that it thinks it's a new javascript file (like function.js?(random number))
Use AJAX to download the file with the function and eval(); it
The only real way to do this is to insert a script element into the document dynamically using JavaScript with a link to a script file containing your function, causing the script to be loaded. One caveat: you must make sure that the filename has the time appended as a query string, otherwise cache unfriendly browsers like Internet Explorer will not reload the script again.
Like others have said, the best bet is to go ahead and insert a new script tag into the page with some kind of query parameter to avoid caching issues. If you're using a JS Library, this technique is actually called "JSONP"; jQuery in particular has a nice method for doing this that gives you an easy way to attach a callback function and such. If you write your own native version, you'll need to watch the readystate of the new script node to know when it's actually loaded.
That said, one thing I'm curious about - and anyone else, please correct me if I'm wrong - why not use the "delete" keyword to kill your function, instead of nulling it out? Something like...
function myFunction() { return; }
Then...
delete myFunction;
Seems to be a more efficient way of cleaning things up, at least from my perspective.

Categories