How to move inline JavaScript from HTML to .js files [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on creating a basic web based game using the HTML5 canvas and JavaScript. Although I have done some work with the HTML5 canvas before, it hasn't been too extensive and so it hasn't required too much JavaScript- meaning I wrote the JavaScript in script tags in my .html file.
With the file I'm currently working on, I'm now getting to the point where I need to separate the JavaScript from the HTML, since when I view the page in a browser, and click the 'start' button on the canvas, although it does perform the function it's meant to, it takes an age to do it... I assume because of the size of my .html file (most of which is JavaScript).
I have moved all of the JavaScript into separate files, with just one or two functions in each file, but I'm not sure how I then use those functions in my HTML page?
My HTML file currently looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<section hidden>
<img id="StartButton" src="StartButton.png" alt="Start Button" width="179" height="180" href="javascript:drawLevelOneElements();"/>
</section>
<script src = "drawLevelOneElements.js" type = "text/javascript"></script>
<script src = "layers&analytics.js" type = "text/javascript"></script>
<script src = "startGameDrawGameElementsDrawStartButton.js" type = "text/javascript"></script>
<script src = "variables&preloadingImages.js" type = "text/javascript"></script>
</head>
<body onLoad="startGame()">
<h1>Home</h1>
<p1>The purpose of this website is to teach users the basic principles of running a business by playing the game below. <br /><br /></p1>
<p2>
<canvas id="gameCanvas" width="1000" height="500" style="border:1px solid">
Your browser does not support the canvas element.
</canvas>
<br /><br /></p2>
<p3>Use this paragraph to enter text that provides the user with instructions for how to play the game. <br />
Update the instructions so that they're appropriate to whatever level the user is currently playing.</p3>
</body>
The script src lines are referencing the JS files I want to use, but when I view the page in a browser, I just get a blank canvas. Could someone point out to me what I'm doing wrong here? I'm not sure how I 'attach' the JS to the HTML when writing it in a separate file.
Edit 21/11/2012 at 12:00
Having made the changes suggested, I tried viewing the page in Firefox again, and in the Firebug console, when the page loaded, it said that there was an "unterminated regular expression literal in one of my JS files. The file it was complaining about contains this JS code:
/* Create a canvas layer to display text */
function displayText(textLayer, message){
var textLayerContext = textLayer.getContext();
textLayer.clear();
textLayerContext.font = "18pt Calibri";
textLayerContext.fillStyle = "black";
textLayerContext.fillText(message, 10, 10);
}
/* Create a canvas layer to display the button */
window.onload = function(){
var stage = new Kinetic.Stage({
container: "container",
width: 179,
height: 180
});
var buttonLayer = new Kinetic.Layer();
var textLayer = new Kinetic.Layer();
}
</script>
<script type="text/javascript">
/*Google analytics code for tracking website. */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31216545-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
and the line it was complaining about was the </script>
It does now work, but making this change doesn't seem to have improved performance much in terms of the time it takes to load an image after clicking the start button... any suggestions?

You're doing it right as is, it could be that your scripts are so big that it takes a while before it renders. The browser interprets the HTML top to down and when it encounters a javascript file it starts rendering that.
In your case I would try to move the javascript files to the bottom of your page and try it again. Also, you have to make sure that the script files are loaded in the correct order.
Also, you should place the <section></section> inside the body and not in the <head> and the <p> should have an id="#n" and last but not least a href on your image when wanting to use a javascript is invalid, use the onClick attribute instead :)
Use the W3C validator service here to validate your HTML.
To then use the functions that you want you "simply" put them either in your onLoad() or if you're keen on using jQuery you can do
$(document).ready(function(){ //perform your functions as normal here });
Have you tried debug your application in Firebug?

Related

Inject external javascript file out of time

I want to load an external javascript. This javascript contains source for an ad. I use a method of injection because the javascript needs the user IP. The javascript code to use is:
<html>
<head>
<script type="text/javascript">var userip;</script>
<script type="text/javascript" src="http://service.get.userip?var=userip"></script>
<script>
var url="http://example.com/abc?user_ip=" + userip;
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.src = url;
headID.appendChild(newScript);
</script>
</head>
</html>
I use a service javascript to get the IP of user ("http://service.get.userip?var=userip" in this example code). Then I added the user IP to the url where I download the javascript.
The javascript is inserted when it revised the web charged with developer mode browser but it doesn't work.
I think the problem is that the JavaScrip injection is slow and this is no time to charge properly.
In my tests I got a proper operation to put a alert before the end of the last script:
<script>
...
headID.appendChild(newScript);
alert("Script is Load!");
</script>
For this reason I think the problem is load time. I also try loops, sleep() and setTimeout(), but I do not reproduce the smooth running that I get with the alert().

letter in quotes appearing just after body tag

We've just launched our new Magento site and the letter 'c' is appearing in quotes immediately after the tag. It's not showing up before on my local machine or on our QA site, I've checked the template files and it is not there either. I'm almost certain it can not be a code issue as we have the same code running locally and on our QA site under version control with GIT.
We've cleared the cache and I've tried checking to see if JavaScript was inserting it with the chrome dev tools but could find nothing.
Strangely, the 'c' is not in the view source document but I can see it with the chrome inspector.
I also don't think it can be coming from Magento CMS Pages/Blocks as it loading immediately after the tag.
thanks for the link. after reviewing the page source, you have an extra c character in the header area:
<!-- END GOOGLE ANALYTICS CODE -->
c<script type="text/javascript">//<![CDATA[
var Translator = new Translate([]);
//]]></script>
Notice that c before the script tag?
Just in support to Benny Lin's very helpful answer.
What was happening was we had our Google Analytics code loading from a template file which contained the stray letter 'c'. We could see this on our local machines as this templates was disabled in the Magento admin settings, but not on production.
This issue seems to demonstrate that when a stray letter appears within the <body> tags on your dev tools inspector and not the view source page it may be because it is in the <head> section. The browser seems to push all poorly formatted html from the <head> section into the <body> section when rendering.
For example if you open the below html in the chrome browser you will see what I mean:
<!DOCTYPE html>
<html>
<head>
c<title>Title of the document in head</title>
<script type="text/javascript">
var test = "test";
</script>
</head>
<body>
The body of the document......
</body>
</html>
Also while we were searching for the stray letter, we were ably to remove it with the below JavaScript that targets the offending XML node in the DOM with an XPath expression and removes that node only.
<script type="text/javascript">
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
jQuery(_x('//html/body/text()[contains(.,"c")]')).remove();
</script>

Javascript loading but not running - rails 3.1

I have in my application layout file an external javascript file witch has several lines of code and at the end runs a function like BooManager.init() no big deal...
the problem is, it is not running the inside code on this javascript file.
this is how i use it:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "iphone4s, apple";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<%= javascript_include_tag "http://widgets.boo-box.com/javascripts/embed.js" %>
but it didn`t do anything it was suposed to do...
i`ve tried in simple html file and it works... what am i doing wrong?
NOTE:
the default way in html is this:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "keywords, between, commas";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
-- EDIT --
the result generated by rails:
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
It's not evaluating the script when loading using the <%= method. I'm not familiar with that syntax, but from the effect, that's what it sounds like. It's treating the script as html rather than code.
jQuery has a script load function that will get a script dynamically from a URL and then eval() it to execute it.
UPDATED WITH SAMPLE CODE
Add jQuery to your app:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
Then use it to load your script:
$.getScript('http://widgets.boo-box.com/javascripts/embed.js');
UPDATE NUMBER 2
I was able to duplicate the problem in this fiddle: http://jsfiddle.net/7x2zT/4/
If what you are trying to accomplish is to get your parameters activated before the script shows the widget - the default one looks like a sidebar, whereas your parameters make it more of a banner, then just make sure you put your parameters above the <script src stuff.
If you must be able to load dynamically, then you're going to have to figure out where the bug lies in the embed code, or if there's some other activation method. That site's documentation doesn't seem to be in English, so I can't help with that.

safari displays javascript source instead of executing

i have a web application that has javscript interspersed through the page. What happens is that safari will dump the source of the javascript code instead of executing it. I can reproduce this consistently.
The page is a mashup of different forms of content:
it loads flash videos using osflv and is generated via a php script on the server side. In addition the page also contains calls to Google Map's API to display a map. The content is placed in separate tabs using javascript to provide tab interaction.
I am also using mootools, and not sure if that is potentially causing issues.
Here are the javascript includes:
<script type="text/javascript" src="/js/mootools-1.2.1-core.js"></script>
<script type="text/javascript" src="/js/mootools-1.2-more.js"></script>
<script type="text/javascript" src="/js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="/js/sifr.js"></script>
<script type="text/javascript" src="/js/sifr-debug.js"></script>
<script type="text/javascript" src="/js/common.js"></script>
<script type="text/javascript" src="/js/alerts.js"></script>
<script type="text/javascript" src="/js/swfobject.js"></script>
<script type="text/javascript" src="/js/autocompleter.js"></script>
<script type="text/javascript" src="/js/observer.js"></script>
<script charset='ISO-8859-1' src='/js/rac.js' language='javascript'></script>
rac.js comes from osflv, common.js and alerts.js are custom javascript code that includes custom classes and functions used to either display or manipulate data in the page.
This block of code executes in the page just fine:
<script type="text/javascript">
var whitney = { src: '/flash/whitney.swf'};
sIFR.activate(whitney);
sIFR.replace(whitney, { selector: 'h6#propertyHeadline', wmode:'transparent',css: {'.sIFR-root': {'color': '#1ca9b9' }}});
</script>
This code also executes just fine:
<script language='javascript'>
var src = '/player';
if(!DetectFlashVer(9, 0, 0) && DetectFlashVer(8, 0, 0))
src = 'player8';
AC_FL_RunContent('codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0', 'width', 520, 'height', 440, 'src', src, 'pluginspage', 'http://www.macromedia.com/go/getflashplayer', 'id', 'flvPlayer', 'allowFullScreen', 'true', 'movie', src, 'FlashVars','movie=media/orig/4b845109d99d0.flv&fgcolor=0x1CA9B9&bgcolor=0x000000&autoload=off&volume=70');
</script>
This is the final snippet of code that is embedded in the html towards the bottom of the page before the end of the body tag, Safari will randomly spit out the src code in the browser at any point beyond the good maps script include:
<script src="http://maps.google.com/maps?file=api&v=2&key=googlemapsapikeyblockedout" type="text/javascript"></script>
<script type="application/javascript">
function InitPropertyDashboardTabs(){
mytabs = new TabPanel('DashboardTabPanel');
initializeGallery();
initializeSiteplan();
initializeMap('address blocked out');
}
var map = null;
var geocoder = null;
function initializeSiteplan()
{
var flashvars = {PropertyId:1,BasePath:'/',wmode:'transparent'};
var params = {wmode: 'transparent'};
var attributes = {id: 'SWFSitePlan',name: 'SWFSitePlan'};
swfobject.embedSWF("/flash/FloorplanViewer/FloorplanViewer.swf", "SiteplanFlash", "915", "500", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}
function initializeGallery()
{
var params = {wmode: 'transparent'};..... (more code)
This is what the page with the js dump
(source: oxid8.com)
this is what the page should look like:
(source: oxid8.com)
First, you shouldn't use the language attribute, it's deprecated.
The only thing I can see is that you use application/javascript instead of text/javascript in your HTML (there's a difference between what you specify in your HTML and the MIME-type servers use when sending a Javascript file), but I cannot reproduce any errors on Chromium/Linux with a simple test case like
<!DOCTYPE html>
<html>
<head>
<title>dkdkd</title>
</head>
<body>
<script type="application/javascript">
var i=0;
</script>
</body>
</html>
(Perhaps you can try this, too.)
Just in case: is the script element closed properly? Is all Javascript correct, i.e. does it pass JSLint?
Perhaps you can paste the full source of the HTML page (preferably on something like Pastebin), so we can have a closer look.
I guess I'll give this a shot. I was having a similar problem on some pages that used TinyMCE (javascript or even parts of my html were being displayed on the page)
MY solution was to upgrade the version of TinyMCE that I was using. v3.3 has an overhauled Webkit handler.
The issue so far as I can tell was that TinyMCE was injecting (poorly) additional blocks of javascript into the page.
This (and a handful of similar blocks) is always injected into <head>
<script type="text/javasript" src="http://www.example.com/javascript/rte/langs/en.js" onload="tinemce.dom.ScriptLoader._onLoad(this,'http://www.example.com/javascript/rte/langs/en.js', 0);">
Which, when onload fired, injected the following block into a random location in the DOM, mangling whatever it was placed on top of.
<script type="javascript" src="http://www.example.com/javascript/rte/langs/en.js">
The result of that, as seen in the Webkit Developer Tools was to turn
<td class="tab" nowrap="">
into:
<td class="ta<script stype="text=""javascript"" src="http://www.example.com/javascript/rte/langs/en.js"> "b" nowrap=>"
Since that's clearly not valid markup the resulting garbage was output.
Upgrading my install of TinyMCE from the previous stable to v3.3rc1 fixed the issue.TinyMCE Changelog references a total Webkit overhaul.
edit: By random I really mean random. It inserts the script tag in a different location each time, sometimes breaking content, sometimes not.

Calling Remote Javascript

Basically, Google Adwords give you a code so you can track how well your campaigns are working. You put in on your order thank you page to track and order, so you can see which keywords bring in the most orders. It gives me a code like this:
<!-- Google Code for Purchase/Sale Conversion Page -->
<script language="JavaScript" type="text/javascript">
<!--
var google_conversion_id = xxxxxxxxxx;
var google_conversion_language = "en";
var google_conversion_format = "1";
var google_conversion_color = "666666";
var google_conversion_label = "purchase";
//-->
</script>
<script language="JavaScript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<img height="1" width="1" border="0" src="http://www.googleadservices.com/pagead/conversion/xxxxxxxxxx/?label=purchase&guid=ON&script=0"/>
</noscript>
When the user clicks one of my ads it sets a cookie with the keyword he clicked from etc, and then when he reaches this bit of a JS on the thank you page it realises he has a cookie and does the necessary tracking.
The problem is, for the thing I'm promoting right now the order thank you page is not on my server. I can place javascript on the page to track orders but only in the following format:
<SCRIPT language="javascript" src="xxxx"></SCRIPT>
With the 'xxxx' bit being the only thing I can change.
If I put the Google JS code in a file on my server, and then call the file on my server from his thank you page, will it achieve the same effect? If not is there any way to do this using what I have available?
If you are not tracking prices or anything but just conversions as defined by a page hit, then you could also go the iframe route. Have the client site open an iframe pointing to your server which then includes the googel code. Personally though, I think the pixel option is better, so long as it is not disallowed or ignored by Google (you will have to experiement to find out if this is the case)

Categories

Resources