I have links that when the user clicks them, the page immediately updates by utilizing the DOM, this is what my o2() does.
Problem is I want to seperate content from logic... i.e., i would prefer the content below to be in a .html file. Currently it is in a .js file.
My understanding is that it is good practice to keep structure/content seperate from logic... For example, using advanced registration for Javascript functions as opposed to inline registration.
How do I get the html content below into a .html file?
function l1() {
o2('Ac1_3','<br/><p class="h">ALL YOUR BOOKMARKS IN ONE PLACE</p><img class="i1" src="i3.jpg" alt=""/><img class="i1" src="i4.jpg" alt=""/>');
}
If you're dynamically adding stuff to the DOM using JavaScript, there is no way around keeping that content in the JS file, unless you want to get pointlessly complex.
Personally, I think it's fine to mix content and logic a little, like this, just don't go over the top to the point where it gets confusing.
Related
I have a page with a lots of javascript. However, the page once rendered remains static, there are no moving things or special effects, etc... It should be possible to render the same HTML without any javascript at all using only the plain HTML and CSS. This is exactly what I want - I would like to get a no javascript version of the particular page. Surely, I do not expect any dynamic behavior, so I am OK if buttons are dead, for example. I just want them rendered.
Now, I do not want an image. It needs to be an HTML with CSS, may be embedded with the HTML, which is fine too.
How can I do it?
EDIT
I am sorry, but I must have not been clear. My web site works with javascript and will not work without it. I do not want to check if it works without, I know it will not and I really do not care about it. This is not what I am asking. I am asking about a specific page, which I want to grab as pure HTML + CSS. The fact that its dynamic nature is lost is of no importance.
EDIT2
There is a suggestion to gram the HTML from the DOM inspector. This is what I did the first thing - in Chrome development utils copied as HTML the root html element and saved it to a file. Of course, this does not work, because it continues to reference the CSS files on the web. I guess I should have mentioned that I want it to work from the file system.
Next was to save the page as complete with all the environment using some kind of the Save menu (browser dependent). It saves the page and all the related files forming a closure, which can be open from the file system. But the html has to be manually cleaned up of all the javascript - tedious and error prone.
EDIT3
I seem to keep forgetting things. Images should be preserved, of course.
I have to do a similar task on a semi-regular basis. As yet I haven't found an automated method, but here's my workflow:
Open the page in Google Chrome (I imagine FireFox also has the relevant tools);
"Save Page As" (complete page), rename the html page to something nicer, delete any .js scripts which got downloaded, move everything into a single folder;
On the original page, open the Elements tab (DOM inspector), find and delete any tags which I know cause problems (Facebook "like" buttons for example) (I also try to delete script tags at this stage because it's easier) and copy as HTML (right-click the <html> tag. Paste this into (replace) the downloaded HTML file (remember to keep the DOCTYPE which doesn't get copied;
Search all HTML files for any remaining script sections and delete (also delete any noscript content), and search for on (that's with a space at the start but StackOverflow won't render it) to remove handlers (onload, onclick, etc);
Search for images (src=, url(), find common patterns in image filenames and use regular expressions to replace them globally. So for example src="/images/myimage.png" => |/images/||. This needs to be applied to all HTML and CSS files. Also make sure the CSS files have the correct path (href). While doing this I usually replace all href (links) with #;
Finally open the converted page in a browser (actually I tend to do this early on so that I can see if any change I make causes it to break), use the Console tab to check for 404 errors (images that didn't get downloaded or had a different name) and the Network tab to check if anything is still being loaded from the online version;
For any files which didn't get downloaded I go back to the original page and use the Resources tab to find them and download manually;
(Optional) Cull any content which isn't needed (tracker images/iframes, unused CSS, etc).
It's a big job. I'd love a tool which automated all that, but so far I haven't found one. The pages I download are quite badly made (shops) which have a lot of unusual code, so that's why there are so many steps. You might not need to follow every step.
I am building a website using PHP and JavaScript, and I feel that I have a good grasp on where to include my JavaScript, but a more specific situation has come up that has me confused. I currently have all of my JavaScript in one external file, which is being included on every PHP page.
Let's say that I have a paragraph with an id='myParagraph' and I need to highlight this paragraph in red with JavaScript on page load. This paragraph is only on ONE PHP page and my website has about 50 different pages. I immediately assumed that I should throw some code into my one external JavaScript file, something like:
$('#myParagraph').css('color', 'red')
and the paragraph would be highlighted when that page loads.
My question is: is this the best way to do it? To my understanding, every time I load a page it will be searched for an element with the id myParagraph, yet 98% of my pages won't even have that id. Is this wasteful? Should I instead include the following code:
function highlightParagraph()
{
$('#myParagraph').css('color', 'red')
}
in my one JavaScript file and then put some inline JavaScript in the PHP file with the id myParagraph to call the function highlightParagraph() when it's loaded? That way, only the one page with myParagraph will be searched and highlighted.
I feel like option 2 is the best, but I read all the time not to use inline JavaScript.
edit: I realize that for this example you would just use CSS. I'm just using it to get my question across
You should have a one "big" js file with the infrastructure functions and all the pages should have a reference to it.
Then each page should reference another js file with the functions related only.
The good things about using external js files are:
The files are cached after the first download => Faster surfing.
Separate of concerns, you keep the presentation tier away from the scripting tier.
Another important note:
The best way to change css is with css... not javascript.
I
If you change the element style on DOM ready, just add the element definition
#myParagraph{color: red;}
The problem with inline JavaScript is you might be starting with a few lines now, but in a few weeks or months, it will add up and be a lot of inline JavaScript.
That is bad, because inline JavaScript can't be cached by the browser like JavaScript files that you include with <script src="path/to/file.js" />.
That's bad because you add a lot of content that will be fetched every single page view by the user, adding load on your server bandwidth and slowing page load for the user.
If it's just a few selectors, don't worry; The time wasted on it won't cause any browser to sweat.
Though, if it becomes a lot of code for a different page/module of your site, you might want to split it into a different JavaScript file and include just that file when certain pages are loaded.
That way, the browser will cache that file and save that bandwidth for you and the user.
I wouldn't be too surprised if many people disagree with me (violently even) but I don't have a problem with putting a javascript tag with specific javascript for that page in the header if it will reduce the number of files or overall complexity of the project. Most of the core things that are done everywhere should of course be separated in another file but if it is a one page deal, then I would go for cleanliness.
The same goes for css, if it is specific to that page just put a css tag in the header with the specific changes that differ from the master css file. BTW as everyone is pointing out, this is a case where you want to just use CSS.
I'm trying to build a single-page app that has several views (screens, page contents)
My App's UI has a permanent menu bar and a "view area" which retrieves a view via Ajax, based on menu selections. This works great for simple HTML content and keeps my menu-script running on the background despite which view is being displayed.
But what if my view needs an additional script? How do you load and execute a script as a result of a view change (=a page fragment was loaded as a result of a button click) also, how do I get rid of that script when I choose a different view?
I know I can embed a script-tag into the page fragment and write the code there, but I'm really looking for a more robust way of doing this, preferably so that an instance of an object is created when the view is loaded and then discarded when the view changes.
yepnope.js is a great conditional loader. You could use it to check certain conditions (e.g. view, state) before loading a script. I don't think it has the ability to remove a script that's already been loaded, though.
You can use javascript to add a <script> tag in the same way you would any other tag.
The hardest part is knowing where to place it, but if you have control over your markup, this isn't too big a barrier.
Something along these lines:
function DST(url)
{
var s = document.createElement(’script’);
s.type=’text/javascript’;
s.src= url;
document.getElementsByTagName(’head’)[0].appendChild(s);
}
If you need something to happen automatically when you load that script, you should be able to use a self executing anonymous function to do the job.
(function(){alert('this happened automatically');})();
If you need to pass anything in to the function it would look like this:
(function($){alert('this happened automatically');})(jQuery);
If you really need to discard the scripts, you can delete the nodes, but it might be better to leave them in, in case a user reactivates a view, so you don't have to make the AJAX call and associated HTTP request, allowing the page to load faster.
I am building a Rails app, and it seems that common practice is to have javascript_include_tags listed on top of a page.
Would it makes browers load javascript before loading the document, and thus makes visible elements take longer to load?
Thank you.
As far as I've read on the web, best practice loads javascript files at the bottom of the body tag. This lets almost everything load before executing the javascript, which generally prevents problems accessing items that may not exist if you loaded the script at the top.
A Yahoo post about web page performance suggests including them at the bottom of the page (Source) because they can block parallel downloads of other dependencies if they are at the top.
Looks like some answers were right, but none sums it all up:
How to prevent javascript loading from loading other elements? Simple, put it right before the closing </body> tag. Which usually means a few characters before the end of your HTML page.
Put all your javascript in external .js files. Why? So that the browsers can cache those files even when the HTML page changes.
Aggregate and minify all your javascript files into one. Why? Because the fewer HTTP requests your clients make, the faster the page loads.
Also, you don't have to care about $(document).ready() or window.onload, since all your HTML elements will be loaded before the javascript files (that is, if you put the JS files right before the closing </body> tag).
It's a good idea to use external JS file and to minify it's content.
http://www.quirksmode.org/js/placejs.html
Bottom of the page is also an option like John Fisher said.
If using i.e. jQuery you in any case use $() or $(document).ready(function() which makes sure the page DOM is loaded before you try to use your JS functions.
Rather than embedding the behavior in its markup, try to segregate the script
by moving it to a script block in the section of the page, outside the scope of the
document body, as follows:
<script type="text/javascript">
window.onload = function() {
document.getElementById('testButton').onclick = function() {
document.getElementById('xyz').style.color = 'red';
};
};
</script>
For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.
Basically what I'm after is, following squashing all my JavaScript into one file (or a few files) how can I make a document.observe(dom:loaded({...})) function call for the right page?
So, say I have 5 pages in my website, and each one has a separate JS file. Inside each file is a load of page related functions, and a special function which sets up eventhandlers etc when the DOM has loaded. Obviously if all 5 pages include their own JS files then that's fine. But I want to compact all my JS into one page for versioning and efficiency reasons.
Therefore, in doing this, I would end up with 5 "dom:loaded" functions waiting to be setup. This won't do as the stuff inside these functions is page specific. So, my question is how can I do what I want to do without causing a whole bunch of DOM errors, and false eventhandler setup requests?
Ive considered namespaces and stuff like that but don't really know anything about it/them.
Btw, I'm using the Prototype lib. Oh, and my sites are considerably larger than 5 pages! :)
Thanks,
Lee
Some ideas:
inspect the dom to identify the page. For example, attach an attribute to the body element.
put a script tag in the page that sets a variable.
inspect the url.
when the load event fires, the event handler identifies the page and hands control off to the proper code.
I would give different IDs to the <body>s of the separate HTML files and test in the dom:loaded event the name of the <body> element using $$('body')[0].id.
I have opted to use a php regexp to capture the URI, then use this as the body ID. On my sites, where the page names are static, it means each page will have a unique ID.
I then include a JS file in the HEAD which contains a switch block inside which the appropriate code/functions are loaded. The switch block is inside the document.observe(dom:loaded...) function.
Works a treat!
Thank you again for your help.
I tend to always write my .js with no self activation (so much as possible)...
psuedo-code
namespace('mysite.section.init');
mysite.section.init.pageName = function(){
//stuff to run here...
};
in your home page, at the bottom, or via dom:loaded event simply run mysite.section.init.pageName();