JavaScript File For Each HTML File? - javascript

I have a javascript file that handles the scripting of several HTML files.
I started running into issues as everything is just written out, and nothing is called in functions (so all AJAX calls for instance are called at all pages, even though each call should only be called at one page one).
What is the best way to go about improving/fixing this? Here are the two ways that I thought of doing it:
Create a separate JS file for each HTML file
Put all JS code in functions and call each function respectively
I am leaning towards putting all my code in functions. However, when I did:
<script src="the_source">
call_function
</script>
That didn't seem to work. I put that right before where the responsible HTML was. I originally wrote it in Haml as follows:
%script{:src => "src"}
call_function
How can I get this HTML function calling working?
Or is separating them whereby each HTML file has a different JS file considered a better solution? The problem is that there is a lot of shared code between them. To solve this, I can create a different file with the shared code in objects which can be called from the other JS files as needed.
What is the cleaner approach/solution to this problem?

To call function use:
call_function();
Edited:
<script src="the_source"></script>
<script >
call_function();
</script>
where "the_source" is path to your js file
End edit
To separate the logic in every page i would just create some settings object and put there flag for cases you want to have separate:
//this code should be on every page you need your javascript file
<script src="the_source"></script>
<script>
var settings = {
mode:'doSomething1'
}
call_function(settings);
</script>
in your js file do things depending on the settings.mode value:
function call_function(settings)
{
switch(settings.mode){
case: 'doSomething1':
//code for case1
break;
case: 'doSomething2':
//code for case2
break;
default:
//code for default case
break;
}
}

This depends on your hosting plan:
If it's a dedicated or semi-dedicated server, I would prefer to have a shared JavaScript file (for performance).
If it is any other kind then separate file is faster as it distributes the load of requests in different JS files.
If you don't want to create separated files as it will be messy, I suggest to do the following:
<script src="somewhere">
var page = "<?PHP echo basename($_SERVER['PHP_SELF']); ?>";
Run_Function();
</script>
In somewhere:
function Run_function(){
switch(page){
case "1.php":
//Do Something
break;
case "2.php":
//Do Something else
break;
default:
alert("Unregistered webpage");
break;
}
Good Luck :D
EDIT:
Try up this function to get the file name from the URL:
function FileName(){
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
return filename:
}
UPDATE:
Please check this improved function of the above:
function FileName(){
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if(filename == "" || filename == "Undefined"){
filename = "index.ruby";//or any other extension
}else{
var filename = filename.replace(/%C3%84/g, "Ä");
var filename = filename2.replace(/%C3%96/g, "Ö");
var filename = filename2.replace(/%C3%9C/g, "Ü");
var filename = filename2.replace(/%C3%A4/g, "ä");
var filename = filename2.replace(/%C3%B6/g, "ö");
var filename = filename2.replace(/%C3%BC/g, "ü");
}
return filename:
}
This function might help more people and it is more flexible to use.

I would put your JS code into several different files, one for each page.
This can help your site run quicker (admittedly not by much) because the browser isn't running through tons and tons of code to find the required function.
Also, (and this is just a personal opinion) , a JS file with just a long list of short functions is quite ugly and seems less efficient.
And yeah, include an extra file with the shared code on. Try to make sure nothing is repeated unnecessarily in the files!
Good luck! :)

Related

set file attribute filesystemobject javascript

I have created a file as part of a script on a network drive and i am trying to make it hidden so that if the script is run again it should be able to see the file and act on the information contained within it but i am having trouble doing this. what i have so far is:
function doesRegisterExist(oFs, Date, newFolder) {
dbEcho("doesRegisterExist() triggered");
sExpectedRegisterFile = newFolder+"\\Register.txt"
if(oFs.FileExists(sExpectedRegisterFile)==false){
newFile = oFs.OpenTextFile(sExpectedRegisterFile,8,true)
newFile.close()
newReg = oFs.GetFile(sExpectedRegisterFile)
dbEcho(newReg.Attributes)
newReg.Attributes = newReg.Attributes+2
}
}
Windows Script Host does not actually produce an error here and the script runs throgh to competion. the only guides i have found online i have been attempting to translate from VBscript with limited success.
variables passed to this function are roughly declared as such
var oFs = new ActiveXObject("Scripting.FileSystemObject")
var Date = "29-12-2017"
var newFolder = "\\\\File-Server\\path\\to\\folder"
I know ActiveX is a dirty word to a lot of people and i should be shot for even thinking about using it but it really is a perfect fit for what i am trying to do.
Please help.
sExpectedRegisterFolder resolves to \\\\File-Server\\path\\to\\folder\\Register which is a folder and not a file.
I get an Error: file not found when I wrap the code into a try/catch block.
I tested the code on a text file as well, and there it works.
So you're either using the wrong method if you want to set the folder to hidden.
Or you forgot to include the path to the text if you want to change a file to hidden.
( Edit: Or if Register is the name of the file, add the filetype .txt ? )
If you change GetFile to GetFolder as described in https://msdn.microsoft.com/en-us/library/6tkce7xa(v=vs.84).aspx
the folder will get hidden correctly.

Accessing file with JS when files are a folder deeper than domain

We have a MVC site which uses subdomains. Not in the traditional sub.domain.com but instead we are using domain.com/sub. The source files all exist in the sub folders of each sub domain because each might have some slightly different things. This causes the Dev team to have to place JS directly into the razor pages so the razor code was able to update URLs like below.
var temp = $('div').load('#Url.Content("~/Images/Excel.png")');
Unfortunately using a code like below in a separate JS file tries loading from domain.com and not domain.com/sub
var temp = $('div').load('/Content/Templates/warning.html');
Theses add on to the domains and can change with clients. Is there a way to get the domain plus sub when the files are loaded like that in the JS without needing to place the code into the razor? I'd prefer a separation of concerns because we are loading scripts sometimes which aren't even used because of it.
what I always do when in similar situations is that I create a function in the main.js or whatever name your using for your shared js file, modify the URL in the function and use the function as the initiator:
in the main.js:
var loadFile = function(selector,path){
$(selector).load('/sub'+path);
}
and then whenever and wherever you wanna load a file:
var temp = loadFile('div','/Content/Templates/warning.html');
UPDATE
you can upgrade your loadFile function to let it know if it has to load from the root of the website if needed:
var loadFile = function(selector,path,loadFromRoot){
var root=(loadFromRoot) ? '' : '/sub';
$(selector).load(root+path);
}

How to read the contents of a file inside an epub using javascript

I need to read, inside a page of an epub3 book, the contents of one of the file of that same epub, being some data to process with a javascript function.
Unfortunately, Javascript prevents from loading local files for security reasons. (e.g the File API only allows loading uploaded user files).
But for me in the context of an epub3, it makes sense and I didn't find any information in the IDPF EPUB3 documentation related to this topic.
Any idea ?
OK. Let's clarify:
I have an epub3 with the following structure:
<root>
META-INF
...
OEBPS
pages
page.xhtml
data
data.xml
In page.xhtml, I want to write in Javascript something like:
<script type="text/javascript">
//pseudo code
var indata = readAsText("../data/data.xml"); // how to write that ???
var outdata = myfunction(indata);
</script>
Found the solution for ages, and realized that it had never been answered:
So answering to my own question ;-)
<script type="text/javascript">
/* Load the file using HTTP GET */
$.get( "../data/data.xml", function( indata ) {
var outdata = myfunction(indata);
}, 'text');
</script>

load javascript with paramater in its url [duplicate]

In my HTML file I have linked to the JS with:
src="myscript.js?config=true"
Can my JS directly read the value of this var like this?
alert (config);
This does not work, and the FireFox Error Console says "config is not defined". How do I read the vars passed via the src attribute in the JS file? Is it this simple?
<script>
var config=true;
</script>
<script src="myscript.js"></script>
You can't pass variables to JS the way you tried. SCRIPT tag does not create a Window object (which has a query string), and it is not server side code.
Yes, you can, but you need to know the exact script file name in the script :
var libFileName = 'myscript.js',
scripts = document.head.getElementsByTagName("script"),
i, j, src, parts, basePath, options = {};
for (i = 0; i < scripts.length; i++) {
src = scripts[i].src;
if (src.indexOf(libFileName) != -1) {
parts = src.split('?');
basePath = parts[0].replace(libFileName, '');
if (parts[1]) {
var opt = parts[1].split('&');
for (j = opt.length-1; j >= 0; --j) {
var pair = opt[j].split('=');
options[pair[0]] = pair[1];
}
}
break;
}
}
You have now an 'options' variable which has the arguments passed. I didn't test it, I changed it a little from http://code.google.com/p/canvas-text/source/browse/trunk/canvas.text.js where it works.
You might have seen this done, but really the JS file is being preprocessed server side using PHP or some other language first. The server side code will print/echo the javascript with the variables set. I've seen a scripted ad service do this before, and it made me look into seeing if it can be done with plain ol' js, but it can't.
You need to use Javascript to find the src attribute of the script and parse the variables after the '?'. Using the Prototype.js framework, it looks something like this:
var js = /myscript\.js(\?.*)?$/; // regex to match .js
var jsfile = $$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*([a-z,]*)/);
config = (includes ? includes[1].split('=');
alert(config[1]); // should alert "true" ??
});
My Javascript/RegEx skills are rusty, but that's the general idea. Ripped straight from the scriptaculous.js file!
Your script can however locate its own script node and examine the src attribute and extract whatever information you like.
var scripts = document.getElementsByTagName ('script');
for (var s, i = scripts.length; i && (s = scripts[--i]);) {
if ((s = s.getAttribute ('src')) && (s = s.match (/^(.*)myscript.js(\?\s*(.+))?\s*/))) {
alert ("Parameter string : '" + s[3] + "'");
break;
}
}
Whether or not this SHOULD be done, is a fair question, but if you want to do it, http://feather.elektrum.org/book/src.html really shows how. Assuming your browser blocks when rendering script tags (currently true, but may not be future proof), the script in question is always the last script on the page up to that point.
Then using some framework and plugin like jQuery and http://plugins.jquery.com/project/parseQuery this becomes pretty trivial. Surprised there's not a plugin for it yet.
Somewhat related is John Resig's degrading script tags, but that runs code AFTER the external script, not as part of the initialization: http://ejohn.org/blog/degrading-script-tags/
Credits: Passing parameters to JavaScript files , Passing parameters to JavaScript files
Using global variables is not a so clean or safe solution, instead you can use the data-X attributes, it is cleaner and safer:
<script type="text/javascript" data-parameter_1="value_1" ... src="/js/myfile.js"></script>
From myfile.js you can access the data parameters, for instance with jQuery:
var parameter1 = $('script[src*="myfile.js"]').data('parameter_1');
Obviously "myfile.is" and "parameter_1" have to match in the 2 sources ;)
You can do that with a single line code:
new URL($('script').filter((a, b, c) => b.src.includes('myScript.js'))[0].src).searchParams.get("config")
It's simpler if you pass arguments without names, just like function calls.
In HTML:
<script src="abc.js" data-args="a,b"></script>
Then, in JavaScript:
const args=document.currentScript.dataset.args.split(',');
Now args contains the array ['a','b'].

Finding javascript's origin

Is it possible from a Javascript code to find out "where" it came from?
I needed this to provide scripts that could run folder-agnostic, e.g.:
http://web1/service-a/script.js
http://web2/some-folder/service-b/script.js
And they're linked in:
http://web1/page1.html
http://web2/page2.html
The file script.js is identical in both locations but I would like them to be able to find out where it originates from so it can call the right web service methods (script.js from service-a should call service-a.method while script.js that is served from service-b should call service-b.method)
Is there a way to find out where script.js came from without using any server-side code?
Well, it's kind of a hack, you could grab all the <script> tags in the document, look at which one has the file name of the file, and do the logic from there.
document.getElementsByTagName('script'); is pretty much all you need. The rest is basic JS.
Even more interesting than looping through all of the returned elements (although that's probably safest), is that we can simply only look at the last element returned by the call above, as Javascript guarantees that must be the <script> tag we're in at the time of it being parsed (with the exception of deferred scripts). So this code:
var all_scripts = document.getElementsByTagName('script');
var current_script = scripts[all_scripts.length-1];
alert(current_script.src);
Will alert the source of the script tag used to include the current Javascript file.
You can analyze source of the html where script.js is included for tag and retrieve path of the script.js from there. Include next function in script.js and use it to retrieve the path.
function getPath() {
var path = null;
var scriptTags = document.getElementsByTagName("script");
for (var i = 0; i < scriptTags.length; i++) {
var scriptTagSrc = scriptTags.item(i).src;
if (scriptTagSrc && scriptTagSrc.indexOf("script.js") !== -1) {
path = scriptTagSrc;
break;
}
}
return path;
}

Categories

Resources