Give preference to JS file function over HTML file - javascript

I have two functions of the same name; let's say foo().
One in the HTML file and one in the JS file, which is included in the HTML file. The problem is I want to give preference to the JS file function rather than the HTML file function.
Is there any way to do that, or is there any syntax in JavaScript like [JSFileName].foo(), that may perhaps call the function in the JS file?

Not sure why you want to have two identically-named functions.
The snarky answer is: Just remove the reference to the function you don't want. (If you have control over your html, such a situation shouldn't exist.)
The answer you're looking for: Place the external script tag after the inline script tag.

Make sure the script tag for the js file is after the HTML script tag in which foo is declared.

It's not clear from your question why you have two functions named foo, but based on your [JSFileName].foo() attempt at a solution, I might suggest using objects as namespaces. In your script you could do:
var myScriptFunctions = {
foo: function() {
// do foo stuff
}
}
You can call it with myScriptFunctions.foo() and you won't have two functions competing for the global name foo.

Related

Using Ruby Variables in JavaScript

I'm new to Ruby so I had a question in regards to using some variables throughout my codebase. I have a variable declared in my Ruby file as follows:
#pages = 350
Now, I know that in HAML, I can simply do:
-if #pages = 350, and in HAML with inline javascript, I can do something like:
:javascript
console.log("#{#pages}");
However, I am linking an external JavaScript file in my HAML document, and I was wondering if it would be possible to use my Ruby variables in my external JS document? I need some variables in order to build what I am trying to build. Thanks!
Update as per one of the answers:
In my HAML file, I have the following:
:javascript
printPages(3);
In my external JS file, I have:
$(function() {
window.printPages = function(pages) {
console.log(pages);
}
});
I you are loading static javascript files I really would not recommend trying to insert variables into that code.
Instead, think about how you would provide that to your javascript code.
You could send it to that code as an argument.
<script type="text/javascript" src="./my-external-script.js"></script>
:javascript
runMyExternalFunction(#{#pages})
Or you could add the variable as a data attribute on your page, and your javascript could look for that when it loads.
Haml:
%body data-pages=#pages
JS:
console.log(document.body.dataset.pages) // value of #pages
Update about your javascript:
Using jquery's on page ready event $() for declaring the function is a bad idea. That means that it waits for everything on the page to be compeletely loaded, and then declares the function your page needs.
What you should be doing is setting up all the function that will be needed right away, and then calling those functions when the page is loaded.
They way you have it, the page loads, printPages() is executed (which doesn't exist yet), and then after all that printPages is created and put into the global scope.
So remove the $() from your external script and add it to your HAML instead.
In fact, if your aren't doing anything super fancy with transpiling or bundling, then you can simply declare the function in your external JS file, and it will be available globally. This doesn't work with your code because they way you've declared the function, it would only be available to code within that $() callback.
// js file
function printPages(pages) {
console.log(pages);
}
HAML:
$(() => {
printPages({#pages})
})

Laravel compressing javascript using mix.scripts(); renames function in compressed file

I am compressing a js file like this:
mix.scripts('resources/assets/js/pages/login.js', 'public/js/login.js');
My pre-compressed file contains this function:
function zoomInForm() {
$('#login-page').toggleClass('zoom animated');
........ ........
}
But in my compressed file the function zoomInForm is renamed so I can never call the zoomInForm(); function on my page.
How can I just compress a js file to one line without removing functions?
If the minifier renames the function, it also renames every place that you call it within the JS files.
Generally, you should NEVER have JavaScript outside of your JS files. Not in a script tag, not in an onclick attribute.
If you want to fx. listen to button click, you should create the listener in the JS:
$('#login-page').click(function(){
zoomInForm();
);
While cssBlaster21895 provides you with a real solution to your specific problem, I believe a more correct solution would be to move your JavaScript logic to your JS files.
You can prevent function from being renamed. You can pass uglify options into mix options.
mix.options({
uglify: {
"mangle": {
"except": ["zoomInForm"]
}
}
});
Maybe it can help,but maybe there something wrong with your whole script at all, even double declaring same function, just a guess...
Or try declaring a function the other way:
var zoomInForm = function(){...}
Then call it when you need with zoomInForm() later in the script and see whats happening.

How does jQuery solve <script defer> issue?

So, I have three js files. All three files are attached to html page without defer:
1)jquery
2)file with the following content
ugu={
temp:function(s){
alert(s);
}
};
3)file with the following content
$.ajax(....) //line1
ugu.temp("hello");//line2
So we see, that third file uses objects from 1 and 2. It doesn't have problems with line1. However line2 has errors if I attach 3 js script to html page without "defer", otherwise it throws error that the browser can't find variable ugu.
The question - how can I make work file 3 without "defer"?
What is the order of including your files? In HTML file you should first include jQuery, then file with ugu definition, and the third one at last.
If you are trying to declare ugu in the global namespace you should use var.
var ugu={
temp:function(s){
alert(s);
}
};
File 2 will have to be loaded before file 3 will run. You might consider looking into require.js it is handy for this.

Is there a way to send variables to javascript files?

is it possible to do something like this
to send the value id=3 to the js file
<script src="http://site.com/js/loader.js?id=3" ....
otherwise what's the approach to do that?
No, that won't work.
Just set the variables before you load the file:
<script>var id = 3;</script>
<script src="http://site.com/js/loader.js" ....
Since all the scripts share a global namespace, you'll be able to access the id variable from inside your loader.js file.
Of course you should think about the style and implications of using global vars to achieve that. Using a global object that hold these config variables might be a cleaner approach.
If that is just a javascript file, you can just define the variable before load it.
<script>
var id = 3;
</script>
<script src="http://site.com/js/loader.js" ....
It would work, but not if your .js URL is just for a static file. If you wrote server-side code that output JavaScript, then you could output custom JavaScript based on the query string.
This is probably overkill for what you're trying to achieve.
k so this question has pretty much been answered. But there is another approach, which may or may not be suitable for you. If you want to render script conditionally or fetch a certain script for a certain id. You can declare it in a serverside script
http://site.com/js/loader.js.php?id=1
In the loader.js.php
Just use the following line in the beginning
<?
header("Content-type: text/javascript");//To declare it is a javascript file
$id=$_REQUEST['id'];
?>
//Normal js continues after this
//When you need to use the variable, just use
var id=<?=$id?>

How to split JavaScript code into multiple files and use them without including them via script tag in HTML?

I am making use of constructors (classes) extensively and would like each constructor to be in a separate file (something like Java). Suppose I have constructors say Class1, Class2, ... Class10 and I only want to use Class1 and Class5 I need to use script tags to include Class1.js and Class2.js into the HTML page. Later if I also need to use Class3 and Class6 I again need to go to the HTML page and add script tags for them. Maintenance with this approach is too poor.
Is there something in JavaScript similar to include directive of C? If not, is there a way to emulate this behavior?
You can use jQuery.getScript:
http://api.jquery.com/jQuery.getScript
Or any of the many javascript loaders like YUI, JSLoader, etc. See comparison here:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
You can use something like this:
jsimport = function(url) {
var _head = document.getElementsByTagName("head")[0];
var _script = document.createElement('script');
_script.type = 'text/javascript';
_script.src = url;
_head.appendChild(_script);
}
then use it in your code like:
jsimport("example.class.js");
Be careful to use this when the head is already in the DOM, else it won't work.
Yes: You can create script tags from JavaScript and load required classes on demand.
See here for a couple of solutions: http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
With careful use of id attributes or a global variable that contains "already loaded" scripts, it should be possible to develop a dependency resolution framework for JavaScript like Maven or OSGi for Java.
When we are talking about JavaScript, I feel it is better to include one file that includes everything you need instead of requesting a new file every time you need something that you don't currently have access to.
Each time you send out for another file, the browser will do many things. It checks if the requested file can in fact be found by sending an HTTPRequest, and if the browser has already seen this, is it cached and unchanged?
What you are wanting to do is not in the spirit of JavaScript. Doing what you are explaining will produce addition load times, and you wouldn't be able to do anything until the file has completely loaded, which creates wait times.
It would be better to use one file for this, include at the inner end of the </body tag (which won't cause the browser to wait until the script is done to load the page), then create one simple function that will execute when the page is completely loaded.
For example:
<html>
<head></head>
<body>
<!-- HTML code here... -->
<script src="javascript.js"></script>
<script>
(function r(f) {
/in/.test(document.readyState) ? setTimeout('r(' + f + ')', 9) : f()
})(function() {
// When the page has completey loaded
alert("DOM has loaded and is ready!");
});
</script>
</body>
</html>
you can include one js file into another js file by doing something like this in the begginig of your js file:
document.write("<script type='text/javascript' src='another.js'></script>");
The best approach in your situation is using of compiler of some kind. The greatest one is Google Closure Compiler. This is part of Google Closure Libraty which has structure similar to what you described.

Categories

Resources