Multiple HTML files linked to only one Javascript file - javascript

I want to have functions in an external Javascript file to be linked to each of my html files. However, I want some functions to be linked to one html file while other functions would be linked to a different html file. Do I need to have multiple Javascript files or can I condense them into only one file? When I tried to use one Javascript file every function would run on each of my pages. Is there a way to call a specific function in html without having the whole code? Like with css using #example for the id example in html.
I used this link in my index.html file:
<script type="text/javascript" src="example.js"></script>
While this one was in another html file:
<script type="text/javascript" src="example2.js"></script>
These links are the only Javascript included in my html files.
I think I found the problem. I have an RSS feed that comes through a free website but the function doesn't have anything next to it.
The html file links to the Javascript file with this in it and because the function is blank it automatically runs or that's what i'm assuming.
(function(){
var a=window;
var b="";
for(i=0;i<a.rssfeed_url.length;i++) {
b=b+"rssfeed[url]["+i+"]="+encodeURIComponent(a.rssfeed_url[i])+"&"
}
var c="http://feed.surfing-waves.com/php/rssfeed.php"+"?"+b+"rssfeed[type]="+(a.rssfeed_type?a.rssfeed_type:"")+"&rssfeed[frame_width]="+a.rssfeed_frame_width+"&rssfeed[frame_height]="+a.rssfeed_frame_height+"&rssfeed[scroll]="+(a.rssfeed_scroll?a.rssfeed_scroll:"")+"&rssfeed[scroll_step]="+(a.rssfeed_scroll_step?a.rssfeed_scroll_step:"")+"&rssfeed[scroll_bar]="+(a.rssfeed_scroll_bar?a.rssfeed_scroll_bar:"")+"&rssfeed[target]="+(a.rssfeed_target?a.rssfeed_target:"")+"&rssfeed[font_size]="+(a.rssfeed_font_size?a.rssfeed_font_size:"")+"&rssfeed[font_face]="+(a.rssfeed_font_face?a.rssfeed_font_face:"")+"&rssfeed[border]="+(a.rssfeed_border?a.rssfeed_border:"")+"&rssfeed[css_url]="+(a.rssfeed_css_url?encodeURIComponent(a.rssfeed_css_url):"")+"&rssfeed[title]="+(a.rssfeed_title?a.rssfeed_title:"")+"&rssfeed[title_name]="+(a.rssfeed_title_name?a.rssfeed_title_name:"")+"&rssfeed[title_bgcolor]="+(a.rssfeed_title_bgcolor?encodeURIComponent(a.rssfeed_title_bgcolor):"")+"&rssfeed[title_color]="+(a.rssfeed_title_color?encodeURIComponent(a.rssfeed_title_color):"")+"&rssfeed[title_bgimage]="+(a.rssfeed_title_bgimage?encodeURIComponent(a.rssfeed_title_bgimage):"")+"&rssfeed[footer]="+(a.rssfeed_footer?a.rssfeed_footer:"")+"&rssfeed[footer_name]="+(a.rssfeed_footer_name?a.rssfeed_footer_name:"")+"&rssfeed[footer_bgcolor]="+(a.rssfeed_footer_bgcolor?encodeURIComponent(a.rssfeed_footer_bgcolor):"")+"&rssfeed[footer_color]="+(a.rssfeed_footer_color?encodeURIComponent(a.rssfeed_footer_color):"")+"&rssfeed[footer_bgimage]="+(a.rssfeed_footer_bgimage?encodeURIComponent(a.rssfeed_footer_bgimage):"")+"&rssfeed[item_bgcolor]="+(a.rssfeed_item_bgcolor?encodeURIComponent(a.rssfeed_item_bgcolor):"")+"&rssfeed[item_bgimage]="+(a.rssfeed_item_bgimage?encodeURIComponent(a.rssfeed_item_bgimage):"")+"&rssfeed[item_title_length]="+(a.rssfeed_item_title_length?a.rssfeed_item_title_length:"")+"&rssfeed[item_title_color]="+(a.rssfeed_item_title_color?encodeURIComponent(a.rssfeed_item_title_color):"")+"&rssfeed[item_border_bottom]="+(a.rssfeed_item_border_bottom?a.rssfeed_item_border_bottom:"")+"&rssfeed[item_source_icon]="+(a.rssfeed_item_source_icon?a.rssfeed_item_source_icon:"")+"&rssfeed[item_date]="+(a.rssfeed_item_date?a.rssfeed_item_date:"")+"&rssfeed[item_description]="+(a.rssfeed_item_description?a.rssfeed_item_description:"")+"&rssfeed[item_description_length]="+(a.rssfeed_item_description_length?a.rssfeed_item_description_length:"")+"&rssfeed[item_description_color]="+(a.rssfeed_item_description_color?encodeURIComponent(a.rssfeed_item_description_color):"")+"&rssfeed[item_description_link_color]="+(a.rssfeed_item_description_link_color?encodeURIComponent(a.rssfeed_item_description_link_color):"")+"&rssfeed[item_description_tag]="+(a.rssfeed_item_description_tag?a.rssfeed_item_description_tag:"")+"&rssfeed[no_items]="+(a.rssfeed_no_items?a.rssfeed_no_items:"")+"&rssfeed[cache]="+(a.rssfeed_cache?a.rssfeed_cache:"");
if(a.rssfeed_border!="off"&&!a.rssfeed_css_url){}
document.write('<iframe name="rssfeed_frame" width="'+a.rssfeed_frame_width+'" height="'+a.rssfeed_frame_height+'" frameborder="0" src="'+c+'" marginwidth="0" marginheight="0" vspace="0" hspace="0" scrolling="no" ALLOWTRANSPARENCY="true"></iframe>')
})()
The only problem now is that I don't know how to call the function. Another function I have is called because I have onClick="example()" which is fine for that but the RSS feed needs to load automatically. I don't want to have to click a button to get the feed to appear.

Functions only run if you call them. So you can have one JS file that contains functions that are never called by one HTML file, and nothing goes wrong -- they have no impact on the functioning of the page. The only downside of extra unused code is that is takes longer to load, but that isn't really significant until the file gets very big.

You could have a file named "common.js" that holds all related JavaScript functionality. But you will need separate JavaScript (either in a separate file or embedded in the HTML page itself) to make specific use of the common functionality according to the needs of the different pages.
After seeing some code, one may be able to provide a better answer.

It's more logical to split your javascript code into multiple files where it is appropriate. But you don't have to run any code in your javascript file even if it is linked to your html page if you put your code into functions.
function myFunction()
{
// do something.
}
The code inside this function won't run unless you call it in your html.
<body onload="myFunction()">
...
</body>

I think you can do that for example by adding id or class to the html or body, and then, write conditions, if the element (html or body) contains the id/class execute the appropriate functions.
When are the functions called? On page load?
If you provide sample code, it would be better.

You can use location.pathname and check the path and use switch or if else

Related

Maddening scope issue

Little things like this drive me crazy!
Working with a typical Joomla website and all it's complexity.
Start with a functioning website. Edit a particular javascript file of a template to add a simple function:
function socialShare(title, url) {
alert("goop!");
}
I reference it in a link:
<a class="icon-facebook"
onclick="socialShare('blog-entries', '11-blog-article/15-oppressive-tyranny&title=Triumph Over Tyranny')"> </a>
The function is included along with 37 other external scripts in a file at the end of the page, included within the body element like this:
<script src="/bts/templates/vg_progressive/js/articleRev.js"></script>
I inserted the sociaShare function definition as the first thing in the include articleRev.js file. The list of external scripts include core functionality like bootstrap, jquery etc etc.
I can see the function in the included script file with firebug's debugger & the include line in the page source near the bottom. BUT IT DOESN'T GET EXECUTED!! If I include the exact same function within a element anywhere on the page it works just fine. For some reason the instance in the external script file is not within the scope of that page / article, tho I can see it clearly in the page source.
I can also put the function within script tags as the last thing inside the body and it is within scope and works fine. I discovered I can define the function in a different included javascript file that is found in the very same folder and it also works fine.
Like I said, things like this make me pull my hair out! What can cause this behavior? How can I narrow it down?
As per Ed Cotrel, here are 2 files which [may] be helpful, tho I don't think so. Rename articleRev.txt to .js and pageSrc.txt to pageSrc.html. As for your comments Ed, I believe I've stated the issue as clearly as I can.
The desired behavior is to see an alert box when the anchor tag is clicked. Simple. The anchor tag displays a social media icon based on one of the class definitions. The onclick attribute should call the javascript function socialShare and display an alert box containing a text message with the 2 parameters. The alert never shows up. If the socialSharing function is moved to the main.js script file located in the same folder and included the same way in the same place in the page flow it works. Is that clearer?
1) http://thecomingbitsharesrevolution.website/media/articleRev.txt
2) http://thecomingbitsharesrevolution.website/media/pageSrc.txt

Add script to script that contains document.write won't execute

We're using a webprogram that uses ajax and jquery and the like (Netsuite). I want to change something on a page and have tried to use document.ready and window.load to get an external script loaded on the page. I've tried to load the external script in the head and body.. but the contents aren't written. The external file looks for a specific div id and then prepends some code to that. It never works, because the page itself loads dynamically and the div I'm looking for loads when the rest of the page is done. So window.load, etc. never work...
At last I'm in the program itself that loads parts and pieces and am trying to simply write the external script file in there. Now this time the external file has a simple document.write in it, so it's straightforward. In other words, the script is in the middle of html code in the body of the page. (I know this is a terrible way of doing it, but I've got to try something to get this to work....)
According to firebug, it writes the external file where it should be (check!) and firebug shows me the contents of that file (check!), but ... it never 'writes' it onto the page...
The file just contains this:
document.write('<div id="shpblk" style="border:2px solid #ffa500;border-radius:7px;color:#000066;margin:5px;padding:5px;text-align:left;"><img border="0" width="12" height="12" src="/images/icons/store/icon_exclamation2c.gif">Hazardous conditions blahblah... Potential delays and disruptions can be anticipated.</div>');
What am I missing?
Edit: some more clarification is necessary...:
Situation: I have to be able to put a piece of html on the page every now and then that creates a message.
Environment: What I have is a page that loads a header and footer first (which are set up in separate files) and then it takes a second or so to load the rest of the page. From what I understand, this "rest of the page" is written in a certain code, similar to javascript/jquery.
What I CAN do is: edit the files for the header and footer and put javascript in there to make modifications to the rest of the page. I can access some of the files that contain parts and pieces of the "rest of the page", but this is a huge pile of spaghetti.
What I've tried:
Since I want to be flexible with the html that I need to put into the page, I preferably would like to create a piece of javascript or html or whatever on another site and have the "environment" pick up that code. I can do this with javascript or iframe. But since it's a secure area (https), I thought it would be best to use a javascript file instead of an iframe. So....
I created the javascript file and tried it out in a normal environment where I knew for sure it would work.. and it works like a charm. But when I tried this in the before mentioned "environment", I am running against a wall...
The javascript file has document.ready jquery statement in it and it would prepend the html div to an existing div on the page.
This way it would load the page and write the page.. easy as pie.
However.. since the header and footer load first (which includes the external script file), and then the rest of the page, SOMEHOW the div where the script checks for DOES NOT EXIST YET. So I tried window.load instead of document.ready. Same result.
Now, it WOULD appear ONLY when I refresh the page. So there may be a way to have it refresh the page, but I only want this as the absolute last attempt.
So then I tried to see if I could go around this by changing the script so that, instead of using a document.ready it would just do a simple javascript document.write statement.
Then I call the script in the middle of the body of the page (I put it in one of the files that load in the middle of the page). I know this is not something I would do normally, but wanted to try it out anyway. So.... I would have something like this:
<div id="block1">
<div id="block2">stuff here<div>
<script type="text/javascript" src="https://someotherdomain.com/include.js" ></script>
<div id="block3">stuff here<div>
<div id="block4">stuff here<div>
</div>
Now when I run this, I do not get any errors, but nothing is being done with the contents of that js file. In firebug it shows me the contents of that file though.. so I assume it's being read.
But I have no idea why it doesn't run.
Again.. back to 'normal' practices: I've tried window.load, because this would run the statement after the page loads, HOWEVER.. like I said before, I have the feeling it builds the contents of the (middle of the) page through this somehow and my script runs before this; it cannot find the div (block3) where it would prepend to. Whenever I stop running the page at my script, the div it's depending on doesn't exist yet...
I hope this made sense...
Solution
For the external script file to work as expected, OP will need to load it using an asynchronous script tag like this:
<script type="text/javascript" src="include.js" ></script>
Yet, the file contains a document.write() statement, which is generally something to avoid. A better alternative would be remove document.write() from the file and save it as a plain HTML file. This could then be safely loaded using using jQuery:
$("#include1").load("include.html");
( Requires adding a target DIV to the page where the content should load. )
DETAILS
The question doesn't tell us how the external file is included on the page. And without that information it's difficult to understand the problem or provide a solution ... which is probably why this question has gone unanswered.
Yet, let's assume the the script is being injected into the page on the client side using JavaScript or jQuery. And if that's true then it will fail if not done the correct way.
Let's look at some ways we might add the script to the page:
These script tags will all fail because the file contains a document.write statement and the script is loaded asynchronously.
<script type="text/javascript" src="include.js" async ></script>
<script type="text/javascript" src="include.js" defer ></script>
<script type="text/javascript" src="include.js" async defer ></script>
The browser does load the file, but reports:
Failed to execute 'write' on 'Document': It isn't possible to write
into a document from an asynchronously-loaded external script unless
it is explicitly opened.
This jQuery sort of works. It loads the script, but the document.write implicitly calls document.open, which erases the original content of the page. That's probably not what OP wants.
$.getScript('include.js');
This synchronous method works so long as the document.write is executed on load, i.e., is not inside function called later. So this is a possible solution for OP.
<script type="text/javascript" src="include.js" ></script>

Run javascript code that is specific to the view

In my ASP.NET MVC4 application I got 1 javascript file for my functions across the site.
This works pretty good - however I want to run certain code in certain views.
Usually I would solve this by simply putting a short script tag in the view calling the desired function.
However I load my js files at the bottom of the body tag so this script tag would call a function before it being loaded which would obviously not work.
How can I call individual parts of my js file from different views while keeping my js files at the bottom of the body?
There are a few things going on here.
I would not be putting JavaScript directly in the page. Many reasons for this, and is not the focus of your question, but something I wanted to bring up.
You can have a separate JS file that gets loaded after your main JS file that actually does the call to the functions from "main".
My approach is to tag said views with an id:
<div id="specific-page-name"></div>
Then in my javascript simply do:
if ($('#specific-page-name').length) {
// Run code
}
This way you can still separate your views from js code.
Finally, if I have to use model data in js I can do something like:
<div data-model-data="#Model.Data"></div>
And simply read it as:
$('div').data('model-data');
I'm detailing the answer given by Matt in his comment : in your layout, you can specify that you want some additional HTML content (in your case, that will be your JS). You'll want to add it after your main JS block.
#RenderSection("AddScripts", required: false)
Then in your view, you can add a section and it won't be rendered in the view, but in the corresponding section in the layout (after your main JS block).
#section AddScripts {
<script type="text/javascript">
...
</script>
}

Check Webpage is Actually using Javascript or Not

This is the following example of what I want to achieve.
<html>
<head>
<script type="" src="abc.js"></script>
<script type="" src="pqr.js"></script>
</head>
</html>
Above is one webpage of any domain.It contains 2 javascript path.I want to know wheather this javasripts are actually being used in the webpage OR it is only declaration of javascript files but not calling any of the javascript function in the webpage.
Both of Javascript files and any other <script> tags you include in the HTML will be included and they will execute what you tell then to execute inside JavaScript
You can set a variable on top of each file you include and check whether that variable is set or not in the position you want to know it.
It depends on if you are in control of those source files or not. If you are, then as already suggested you can simply put an alert or any other kind of flag in each file, and see if they occur on the host page.
If you are not in control of those source files, then you can use a javascript debugger to place breakpoints within each of the files and then reload the page. If the breakpoints get hit, obviously the code is being executed.

Where do I put the $(document).ready()?

I've been trying to add JavaScript to my HTML/CSS, but been running around in circles.
My current set-up is where the html, CSS, and JavaScript files (2 files; my JavaScript code, and jQuery's code) are all separate, but linked to each other via the html page.
So here are my questions:
1) Do I put the link to the jQuery code within the html head? Or within my JavaScript code page?
2) Where does this code go? The html page, or my JavaScript page?
$(document).ready(function(){
//Code here
});
3) Above, by 'code here', they mean JavaScript code, right? Not my html code?
4) I've read about initializing JavaScript code at the bottom of an html page. From what I take though, I don't have to do that with jQuery's .ready function, right?
You should like to your JavaScript files either in the <head> or above the closing </body> tag.
The code can go anywhere really, but I would suggest an external JavaScript page.
Yes
This is correct.
When Javascript code is executing in your browser, all of your included Javascript files and any code you write in-between those "script" tags in the HTML document is going to be executed as though it were all part of one giant file (same namespace). So in some sense, it doesn't matter whether you write your code in the HTML document or whether you write it in an external file that you include - you're free to do either, and it will be executed the same. You can balance maintainability, reusability and convenience (think about what functions you write that you might want to reuse on other pages) and do whichever you feel is best.
To make this concrete - this is one valid way to write your Javascript, if you wanted to write the code inside your HTML file:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('Document Ready!');
});
</script>
</head>
<body>
...
Here's the intro at the jQuery site, for reference:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Writing your Javascript code at the bottom of the HTML page was/is a technique for getting it to execute as soon as the document is loaded, which is unnecessary when using jQuery's '$(document).ready' (that's what it does - it abstracts the business of getting Javascript functions to execute on page load, and implements it in a cross-browser way).
See: Introducing $(document).ready() for more.
It doesn't really matter where you place your jQuery code. If you place it in the head tag, it'll automatically load everything. If you decide to place it all in an external JavaScript file, you need to link it with a <script type="text/javascript" src="my_file.js"></script> tag.
The 'code here' part is only for JavaScript. What the code is saying is that when the document is ready, run this function. The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser).
You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed. It's nonessential.
$(document).ready(function(){
//Code here
});
goes in your javascript file. All javascript code that should be executed once the page has loaded goes where the //Code here comment is.
Perhaps a quick jQuery tutorial would be in order?
Or, you can put your script tag in the bottom of your body, and not have to use the $(document).ready() function.
Put in the head. This is the most stable way and it works. Some people may disagree and say it is slower, etc, but I have found this to always work.
Where you put your code is up to you. You can put in your head with a
<script>Code here</script>
or in a separate file and include it with
<script src="reftomyscript.js"></script>
Yes, put your javascript code in this, either in the head or in a separate file.
Yes, and see (1)

Categories

Resources