What I want to do is to separate all my JavaScript from the page, so it works for all with disabled JavaScript, but also be able to compile it using closure compiler’s advanced compiling (http://closure-compiler.appspot.com/home).
Here is how I started:
From…
<a href="javascript:doMultiple('download', 'release');">Create archive</a>
to…
<a class="javascript doMultiple download release" href="ca.php">CreateArchive</a>
Then I loop all objects to find what have the class javascript first, etc: (links is an array of the a tags)
for (i = 0; i < links.length; i = i + 1) {
if (links[i].className.substr(0, 10) === "javascript") {
jsArray = links[i].className.split(" ");
links[i].style.display = "inline";
if (links[i].addEventListener) {
links[i].addEventListener("click", window[jsArray[1]], false);
} else {
links[i].onclick = window[jsArray[1]];
}
links[i].href = "#";
}
}
With this method javascript compressors will remove the function doMultiple because it’s unused because it dosnt know I have a class with that…
And my question is, how can I solve this, and if I can’t, can I somehow get rid of the window[jsArray[1]] and do solve that in another way? Because I think that is not the best way to do it.
A class can also be:
<a class="javascript popUp register.php 350 300" href="register.php">Register</a>
So I want to use this method for adding all JavaScript dynamically.
Best regards,
Johan Svensson
You shouldn’t need to make things complicated. It’s better to attach an event to your DOM element.
I would highly suggest you to use a JavaScript framework like jQuery, or even you can achieve this using plain JavaScript.
For instance
OR
And for JavaScript:
And if you use jQuery, life is simple
That’s it, and also mind that there’s no JavaScript code in your HTML.
Question 2
For Google Closure Compiler, you have to use exclude the function that you don’t want to be compiled/minified.
You should have a
.JSfile which will contain the function names to be excluded.Your
exclude.jsshould contain the signature of the functions like:And run this from your command line to compile using closure compiler
Hope this help. Please feel free to ask any question