.load() loads after scripts / in-page scripts do not work - javascript

Brief
Imagine your first website vastly growing in the amount of code, however particular parts you want to globally modify such as a menu seen on every page. So I've taken my header and added it to it's own file and load it using:
// Load Header
$(".Header").load("assets/HTML/header.html");
So I've got my header, added it to it's own place to allow a bit of CMS to my website.
What Makes It Tick?
Dependant Files:
jquery-1.11.0.min.js
jquery-migrate-1.2.1.min.js
jquery-ui-1.10.3.custom.min.js
jquery.ui.widget.js
jquery.ui.selectmenu.js
In page script for drop downs and whatnot
The Problem
The header is loading presumably after all my scripts have loaded regardless of the several places I've tried and tested adding to fetch the header code.
I'm HOPING this is enough to insight some help, some possible problems many encounter as posting my link, it is massively subject to change! Please specify how I could make this question anymore local to Stackoverflow, however for now my live version can be found here.

I don't think that is good implementation of jQuerys load() method.
Have you tried using this pattern instead of using jquerys .ready()?
$(window).load(function(){
# your code
$(".Header").html(yourContent);
});
From jQuery API:
"Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready."
Just remember to put this statement outside of $(document).ready(function() { ... });.

Related

jQuery loses ability to read HTML and CSS tags inside AJAX script after location hash change

I'm experiencing some issues regarding an AJAX script I'm working on.
The page loads perfectly well, and all needed scripts are loaded the same for basic page functionality inside AJAX script, but after hash change, jQuery behaves awkwardly.
Let's take this example.
The custom jQuery script writes an inline CSS propriety for a specific DIV at page loading:
Now, I load the login page for example:
I get back to the main page and inline style disappears as well as the basic loaded functionalities cease to exist after Ajax call:
*
Any experience on this? Does anyone have a clue why this happens? Or even near it... Seems the script unloads on page/hash change, which I don't believe. Or enters in double loop, therefore doubling the classes for HTML. I don't get it.
Already searched a lot and went trough the coding and is fine becasue it works fine alongside with basic HTML. Would appreciate some thoughts on this matter.
Thanks!

The difference between async loading js files and loading in footer [duplicate]

Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?
Put Scripts at the Bottom
The problem caused by scripts is that
they block parallel downloads. The
HTTP/1.1 specification suggests that
browsers download no more than two
components in parallel per hostname.
If you serve your images from multiple
hostnames, you can get more than two
downloads to occur in parallel. While
a script is downloading, however, the
browser won't start any other
downloads, even on different
hostnames. In some situations it's not
easy to move scripts to the bottom.
If, for example, the script uses
document.write to insert part of the
page's content, it can't be moved
lower in the page. There might also be
scoping issues. In many cases, there
are ways to workaround these
situations.
An alternative suggestion that often
comes up is to use deferred scripts.
The DEFER attribute indicates that the
script does not contain
document.write, and is a clue to
browsers that they can continue
rendering. Unfortunately, Firefox
doesn't support the DEFER attribute.
In Internet Explorer, the script may
be deferred, but not as much as
desired. If a script can be deferred,
it can also be moved to the bottom of
the page. That will make your web
pages load faster.
EDIT: Firefox does support the DEFER attribute since version 3.6.
Sources:
http://www.w3schools.com/tags/att_script_defer.asp or better:
http://caniuse.com/#feat=script-defer
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
Only load jQuery itself in the head, via CDN of course.
Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.
There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.
For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.
There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?
Much ado about nothing, stick jQuery in the head and let your js freedom reign.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.
In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.
Just before </body> is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.

How do I change and run js and css (less) files with ajax (using jquery)

When I click a botton I make an ajax call which loads different html code inside a div with the id 'main'. I have no problems getting the html code to show, but I can't find a way to change/add/include css and js code to my current page.
Or actually, I have found many different ways but non does what I want it to do.
First I tried to send over the link and script tags as strings inside a json object (with my other html code) and inserted them where I wanted them to be.
$('#main').children().remove();
$('#main').append(data.html);
$('body').append(data.js);
$('head').append(data.css);
it seems like this inserts them correctly when I 'inspect elements' and look under the 'sources' tab in the browser (chrome), but they don't execute/run.
Then, I tried to add id attributes to my css and js elements and then change the href and src attributes respectively (I have tried doing this both before and after my ajax call but both inside the click event). This allowed me to take away the css and js which belonged to the previous html code that was inserted in the div which is what I want.
$('#lessAjax').attr('href', 'location/style.less');
$('#jsAjax').attr('src','location/main.js');
and they are also included when I 'inspect elements' and look under the 'sources' tab in the browser (chrome), but obviously they don't execute/run either since this is pretty much the same thing as I did in the first example (only that now the code which is not used in my new view is taken away).
I then thought I had found a solution to the js file after finding the $.getScript() method since it executed my script which is directly under $(document).ready(function(){....}, but I noticed that the file cannot be found anywhere when I 'inspect elements' or when look under the 'sources' tab in the browser (chrome) so there is no way to take away or debug the code.
I have also tried
$('<link href="location/style.less" type="text/css" rel="stylesheet/less">')
.appendTo("head");
which includes the file but doesn't execute/run/work either.
I don't want to just include css and js code within script and style tags. I want to be able to switch css and js files as I change html code inside this div with Ajax (jQuery).
I have tried many more things in the 5 hours I spent trying to do this but I can't remember them all now. Surely this must be a common thing to do? Or are there any reasons for why I really shouldn't do this?
Any help would be much appreciated.
jqueryMobile: How to load external Javascripts
Can I load external stylesheets on request?
However please consider using a templating engine for content like this. There are many out there like underscoreJS and even frameworks that support them like Knockout, AngularJS and Backbone.
$("#somebutton").click(function(){
var path = 'path to css';
$.ajax({
url: path,
type:'HEAD',
error: function()
{
alert("failure")
},
success: function(result)
{
alert("success")
}
});
})

Recall external JS files after page transition finish

I have tried to implement this kind of script (Page Transition): here
Everything is going fine as demo provided. But only 1 problem that I cant figure out is:
I have 2 HTML files which is index.html & index2.html. On index.html I put the link with the page transition effect after clicked it goes to index2.html which is on index2.html I was put in some alert script using body on-load method.
Supposedly in normal practice, the alert will appear as normal we seen for debuging. But it doesn't appear anything. Seem like it doesn't load any script after page transition done.
Can somebody give me a clue to solve this? What I have tried is using :
location.reload(); window.location.reload(); etc.. till I don't have idea to fix this :(
*location.reload() works on desktop browser but doesn't work on mobile. My priority target browser is on mobile version.
Please help & Many Thanks
for demo purpose and needs help : here
It wasn't executed because the page never really loaded. The way that page transition script worked is by loading the content of the target page via ajax, replacing the entire content of the page with it.
From the page you provided, it seems like the script accepts a callback function to be called when the page finishes loading, you can put your 'loaded' script there. But keep in mind, what is being executed is the script on that first page.
I don't know what you are trying to make, but I guess it would be better for you to look into a proper single page app with URL matching. There are frameworks like Backbone.js that can help you with this.

Jquery Mobile - $.mobile.changepage not loading external .JS files

So I am having a hard time getting $.mobile.changePage to function properly. I call it like this:
$.mobile.changePage( "DataformsM-AddRecord.html", { transition: "slide"} );
But for some reason, when the HTML page is loaded, none of the external .js (the files that I wrote to actually do something) are included. I am following the significant loading conventions of
-Jquery
-(CUSTOM JS)
-Jquery Mobile
Does anyone know why this is not getting loaded properly? Also, the pageshow function is not getting fired either, which is strange. It looks like this:
$("div[data-role*='page']").live('pageshow', function(event, ui) {
loadFormFields();
});
Now the page is rendered, but none of the functional things happen. If I hack it and do something like this:
document.location.href="DataformsM-AddRecord.html";
It will function properly.
jQuery Mobile does not pull the whole page into the dom, it grabs the first data-role="page" element and its descendants and pulls that into the current dom.
So any scripts in the <head> of the document will not be included.
I generally put all the functional JavaScript for my site on the index page and then when external pages are loaded into the dom they can benefit from the already loaded scripts.
Also, you can place JavaScript code inside the data-role="page" element and it will be included when jQuery Mobile does its AJAX load of the page.
UPDATE
A good system for this is to put all of your JS into an include file and include it on each page of the site. It will be ignored if pages are brought into the DOM by AJAX, but if someone refreshes somewhere in your site, the JS will be available.
So building off of what Jasper so wisely noted above, I came up with a working solution.
Basically I Load up all of my JS and CSS files into the index page to start. Now when you load, this method will be triggered for the pageshow
$("div[id*='page1']").live('pageshow', function(event, ui) {
setTimeout(function() { window.scrollTo(0, 1) }, 100);
doStuffWhenPageintializes();
});
Once I call the $.mobile.changePage( "someOtherPage.html", { transition: "slide"} );, the pagehide method will get fired for the page1 object. This is where you can trigger the method to initialize the page you are transitioning to.
$("div[id*='page1']").live('pagehide', function(event, ui) {
setTimeout(function() { window.scrollTo(0, 1) }, 100);
loadStuffForNewPage();
});
Now you can remove the document.location.href="external.html" line and simply use the native JQM call. Hope this helps some people.
Kindly repeat the head section with all the scripts in each html page, since change page will cause reload of pages and will re create head section...
a simple change page like this would then work:
$.mobile.changePage('abc.html', {
transition: 'slide'
});
It seems that there is no "right" way provided by JQM to load external html files. Thanks a bunch to Jasper for the solution.
JQM suggests an AJAX reload if we want to switch to external pages, like:
<a href="foo.html" rel="external">
or
<a href="foo.html" data-ajax="false">
I tried both but they didn't work - I"m programming for native apps, so maybe it may work for web apps?
I solved this by putting script in the head section of last loaded page that helped and worked for me. JQM is not getting the head section of recently loaded page in the DOM so not bringing the JS content of the recent page. By putting all the script in an External JS file or by putting it in the head section of very first page might do the trick for you.
I too am looking for this solution the "correct way" for loading external pages. However, I will concur, that your hack does indeed work. I'll take the hack for now:
$(document).ready(function(){
$("#page1").bind('ended', function(){
$.mobile.changePage($(document.location.href="external.html"), 'fade');
});
});

Categories

Resources