jQuery in CSS style sheet - javascript

I’m working on making my web site fade in and out every time I click a link to another page. I need to use jQuery to do this. Do I need to put the jQuery code on every page or can I write jQuery into the CSS Stylesheet? If so, how do I format the CSS Stylesheet to accept jQuery?
I’m experimenting with the code from this forum post: Fade Out between pages – CSS-Tricks
Edit to question based on comments
So, I now know that I can’t put JavaScript in CSS file. What’s the best way to put JavaScript code that applies to all pages in a site? I want to write this transition code and then not have to write/edit it into every page.

Save the JavaScript in a file with the extension .js, for example main.js. Then give it a public URL, in a similar way that your CSS files are accessible from a URL. An example URL: http://example.com/js/main.js. You might do that by putting it in a js folder in your public_html folder on your server – it depends on your server.
Then, near the end of each page’s HTML, right above </body>, add this HTML tag:
<script src="/js/main.js"></script>
The script tag with a src attribute will load the JavaScript at the given URL and then run it immediately.
I recommend putting it at the end of your <body> element and not inside the <head> because the script prevents the rest of the page from loading and displaying to the user while the script runs. If you make the script run only at the very end of the page, the page is already loaded and the user can see all of its content.

you need to do a $.fadeout on the window.beforeunload event, bye
PD: in a js file, not in a stylesheet, you can´t use JS in a stylesheet. bye.

Related

Where to insert JavaScript Libraries and CSS in my HTML code?

I am little new to web development and when I was searching internet about other topics, I have seen many people has put popular JS Libraries in Different Places of their websites.
eg: Inserting JS Libraries on the Very Beginning or Start of the <head> </head> section. (Before loading any JS Code or a CSS File)
eg: Inserting JS Libraries on the End of the <head> </head> section. (After loading all JS Codes and CSS Files)
eg: Inserting JS Libraries on the End of the <body> </body> section. (After loading all JS Codes, Texts, Images, Videos, CSS Files etc...)
So my question is this.
What is the best practice for inserting (where) following JS Libraries, Plugins and CSS Style Sheets to a web page for the most faster loading times and other advantages? - Please mention the reason -
JQuery and it's Plugins
Bootstrap 3.js
Modernizr.js
Angular.js
And another widely used JS Libraries which I couldn't mention here...
Normalize.css
reset.css
bootstrap.css + more
Thank You..!
There is no so called "standard" method. The choice of where to put the lines boils down to one question: When will I need the library?
You see, web files loads line by line, let's take the following as an example of what I mean:
<script>
document.getElementById("target").innerHTML = "changed"
</script>
<p id="target">unchanged</p>
#target isn't altered because the script was loaded before the element did. Web files loads procedurally. When the line of JavaScript is loaded. It is executed immediately, but the target element isn't. So it couldn't change the element.
Even with jQuery, there is the same problem:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#target").text("changed");
</script>
<p id="target">unchanged</p>
Therefore, we often use $(function(){}).
Back to the loading problem
People who put their <script> tags or <link> tags in the body (in front) or in the head, wanted to execute the script immediately, sometimes they won't use $(function()) or document.onload
People who put their <script> tags or <link> tags in the body (in the end) wanted to ensure all elements are loaded then execute the script or load CSS.
Conclusion
You should load independent resources such as jQuery first, then load dependent resources such as jQuery plugins. Then you try to decide when you want the resources to start loading, then put the lines in places.
You should put CSS links in the <head> tag because you don't want visitors seeing unstyled content before loading the CSS files.
If you can't decide or don't care about the time, put every <script> and <style> tags in the <head>.
Here is another post you might be interested in: Load and execution sequence of a web page?
CSS can added inside header tag & but put all JS Libraries and custom files just before closing closing body tag
<body>
//other tags
<script> All Scripts here </script>
</body>
By doing so you wont have to check if DOM content has loaded.
It decrease page loading time.Otherwise a js need to be completely loaded before DOM loading.
It also makes sure that all events are attached properly to DOM element.
I think this address all your concern specially the third one
CSS Sheets go in the < head >. The order of the CSS files matter so libraries should be put in first then you can put in the specific ones you have.
Javascript links go in the < body > but place them at the very end. That way your HTML content loads first then the JS loads and it will recognize all your selections. It is more efficient to do it this way.
The most important thing to note when placing your css and script tags is that the order you place them determines the order they are loaded in and if style or code is loaded later it over writes the code written before. So if you have css styling that assigns different styles to the same attributes of the same element then it is the one loaded later that takes effect. And with script tags it's important to remember that for dependency reasons. You should load the dependencies first so that they are there for the other scripts to use. Aside from that normally css tags are in the head and script tags at the bottom of your body element

How to check that all javascript/css loaded correctly

I am trying to find out a solution which will notify user if some resources did not loaded correctly.
Already I founded following methods:
For CSS I found example in Trello source:
<div id="nocss">
Your browser was unable to load all of Trello's resources. They may have been blocked by your firewall, proxy or browser configuration.
<br>Press Ctrl+F5 or Ctrl+Shift+R to have your browser try again.
<hr>
</div>
And in last downloaded CSS there is a following CSS:
#nocss {
display: none;
}
For JS i founded following article: The best way to load external JavaScript, but I am not sure about it.
UPDATE
Small update: the best solution should work also with files from CDN, because they are the biggest problem. I had a site in which I added jquery and in companies behind the firewall it was blocked.
You can do pretty much the same with your javascript like you do with your css.
$(document).ready(function(){
$("#nojs").css("display","none");
}
This code uses jquery. If put into the beginning of your javascript file it hides a div like your css does once the javascript is loaded. (of course you need a <div id="nojs">)
You might want to add a class to the body for each successfully loaded JS file (in each JS file write code to add additional CSS class to the body element like so $(document.body).addClass("SomeClass")). Then simply check
if (!$(document.body).hasClass("ALL YOUR CLASSES")){
$("nojs").show();
}
This should do the trick.
If you don't have access to the files and cannot modify them then why do something like the following:
<script>!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script> (Taken from HTML5 Boilerplate)
Rather than being dependent on any other method, can you use
window.onload=function(){SomeJavaScriptCode};
or
<body onload="SomeJavaScriptCode">
Above ones will only execute after loading all contents of your page. (onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).)

Add query string to script tag link in asp.net to break Cache

Hope someone can help me on this. I manage an ASP.Net website and usually update script files and css files very often. I add current time appended into a single string as a query string parameter (eg: profileImage.jpg?123021) which makes the browser to look for the file without getting it from cache.
How can I do the same thing to all script tags and css links from the server side so that it loads the latest version of the file.
Any help appreciated.
Amila
If your asp.net website uses Master Pages, it should be easy to make these changes in the Master Page file. Look a file with the extension .master. If you are not sure how to make the specific edit, post the <head> area from the master page markup in a new question.
MSDN Master Pages: http://msdn.microsoft.com/en-us/library/wtxbf3hh(v=vs.100).aspx
If your site does not use master pages, then you'd need to create some server-side logic that affects the <head> section of the page. Below are some links to related QA's about injecting script and styles from the server side.
ASP.NET: How to (programmatically) attach a <script> tag, containing a link to .js, to <head>?
How to Add script codes before the </body> tag ASP.NET

Load pages via AJAX and execute javascript and CSS

I've been searching for a while now, but I can't figure out how to load an entire page via AJAX and still execute all javascript and css.
Mostly I just end up with the plain text without any CSS.
Is there a way to do this? I tried jQuery.get, jQuery.load and jQuery.ajax, but none really work like that.
I have a different solution. You may try it with an iframe. Use jQuery to append an iframe script including all relevant codes into some part of your page (like some div). This may do it for you including CSS, like;
$('<iframe src="your_page.html"/>').appendTo('#your_div');
Or you may try something like;
$('<iframe src="your_page.html"/>').load(function(){
alert('the iframe is done loading');
}).appendTo('#your_div');
I have solved similar problem as following.
Download the webpage over ajax
Iterate it over and find any <script> and </script> tags
Get content from within these tags as text
Create new <script> element and insert there the code
Append the tag to your webpage
Another thing is you will need to somehow call the script..
I have done it this way:
I set standardized function names like initAddedScript callback which I am calling after appending the script to the page. Same as I have deinitScript called when I do not need the code (and its variables,..) anymore.
I must say this is awful solution, which likely means you have bad application architecture so as I have had:)
With css is it the same, but you do not need any handlers. Just append the style tag to your documents head.
If the page you load doesn't have any style data, then the external stylesheets must have relative paths that are not correct relative to the invoking document. Remember, this isn't an iFrame - you aren't framing an external document in your document, you're combining one document into another.
Another problem is that loading your complete page will also load the doctype, html, head, and body tags - which modern browsers will cope with most of the time, but the results are undefined because it's not valid HTML to jam one document into another wholesale. And this brings me to the third reason why it won't work: CSS links outside of the head section aren't valid, and the misplaced head section caused by your haphazard document-in-document collage.
What I'd do for compliance (and correct rendering) is this, which would be implemented in the Success callback:
Copy all link elements to a new jQuery element.
Copy the contents of all script in the head section
Copy the .html() contents from the loaded document's body tag
Append the link elements (copied out in step 1) to your host document's head
Create a new script tag with your copied script contents and stick it in the head too
Done!
Complicated? Kind of, I guess, but if you really want to load an entire page using AJAX it's your only option. It's also going to cause problems with the page's JavaScript no matter what you do, particularly code that's supposed to run during the initial load. There's nothing you can do about this. If it's a problem, you need to either rewrite the source page to be more load-friendly or you could figure out how to make an iFrame suit your needs.
It's also worth considering whether it'd work to just load your external CSS in the host document in the first place.
I suppose you are looking for something like this:
your page div --> load --> www.some-site.com
After a quik search the closest solution seems to be the one by "And": Load website into DIV
You have to run a web server and create a proxy.php page with this content:
Then your JQuery load() function should be like this:
$("#your_div_id").load("proxy.php?url=http://some-site.com");
NB. I have tested this solution and it should not load all the CSS from the target page, probably you'll have to recreate them. For example the image files stored on the remote server will not loaded, I suppose due to authentication policy.
You will be also able to view only the target page without the possibility to browse the target site.
Anyway I hope this could be a step forward to your solution.
Get your entire webpage as text using ajax
document.open();
document.write(this.responseText);
document.close();
OR
document.documentElement.outerHTML = this.responseText;
But you need to change the path of css and js pages in original webpage if the resulting webpage is in another directory.

Dynamically adding and removing javascript/css with Jquery (or other library)

I am trying to compare having a 1 page app with clientside routing to having a asp mvc app which just routes to html files, to see which is more appropriate for my current project. As I have no need for any Asp Mvc features its all javascript/html which communicates with a web service.
However one problem I can forsee with the one page app is that my site isnt really 1 page, so I would be having to have on main index.html which contained all shared resources. Then dynamically load in new pages based on the hashbang and add in any required scripts and css. This doesn't seem to hard as Jquery I believe provides a .load() method or something similar to get external resources... my problem though is getting rid of them once I am done...
Is there any way to do this, so you target ONLY certain script/link tags, can you give them Ids or something?
Any help on this would be great...
== EDIT ==
Added a simple example to show what I mean:
<!-- Script already in page -->
<script type="text/javascript" src="scripts/script1.js"></script>
<!-- Dynamically added script -->
<script type="text/javascript">
// some javascript
</script>
How can you tell which ones you should remove? If you could apply an id or uniqueness to each script then it may be ok, but thats what i am getting at with this question.
There are zero benefits to "removing resources." When a script has been loaded, removing the script tag from the page later has no purpose--it won't improve your browser performance at all, nor will it harm it to keep the files around.
Simply add your resources as needed and write your code such that it won't execute erroneously.
I'm not shre i understand why you would like to do that but link element (for css) and script (for js) are elements like any other and they can be deleted with remove().

Categories

Resources