JQuery Mobile loading style and scripts on refresh - javascript

The way JQM loads pages is by getting the element with the attribute data-role="page" via ajax, and not the whole document.
So, how do I make JQuery Mobile load the styles and scripts from any page (or a refresh), rather than only loading them in the entry point (index.htm)?

Just put them into the BODY tag.
It is described in my other answer: Why I have to put all the script to index.html in jquery mobile

Thanks, I had all my JS on one file, but the jquery, jqm, and jqm css files needed to be on each page too. What I ended up doing was including a script on each page body that checks if the scripts exist. If they were not there, they would be dynamically added.
It would be like this
if (document.getElementsByTagName('script') < 3)
{
createElement
setAttribute
append inside head element
//repeat for each script / styleshet
}
else
//do nothing
If I went the route of including all the files in the body, there would be a redundancy of the assets being requested on each page change. I believe this gets around it. It seems to work so far.

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

Import stylesheets and javascript on the fly

I have a website whose navigation is all done via ajax (with jquery); each page is dynamically loaded into an element on the page. While I have a universal stylesheet and JS scripts, each page also has a page-specfic stylesheet and JS script. What is the most effect/efficient way to load these page-specfic scripts and stylesheets? On page load, most of the page-specfic scripts/stylesheets will not be needed. A page's scripts/stylesheet will only be needed when a user loads in (via ajax) a particular page. Should I load every single script and stylesheet at page load?
Another option would be to simply append appropriate <link> and <script> elements to the head when a page is dynamically loaded; however, would they be called? Also, would I need to remove the <link> and <script> elements when a different page is called (via ajax)? For the scripts, I could use jQuery's .getScript() function. What is the best approach to this in terms of efficiency and cross-browser support?
Thank you!
Js and CSS are one time load and are browser cached (depends on your server conf as well)
So if you have an ajax, with just 1 JS inclusion. You could
Insert this JS at the footer of your home page (lazy loading; pre-emptive thinking .. faster 2nd pages)
Bring the include JS tag along with ajax response. (nothing complex here. browser makes fresh JS call)
Combine all your JS/CSS into one combined JS, push it to home page head tag (eyeing performance and caching)
once document ready, do similar to #1 using getScript() as you suggested
Well one way I know of that this can be done is with RequireJS,
but the downside is that all the JS you have need to be defined as AMDs.
Don't know if you know anything about RequireJS, but its quite a neat library,
you can imagine it as a dependency injector and loads files in async way.
If you are interested you can check their docs:
Intro
CSS
Before I have commented what you could do with the CSS.
This is how you can work with js:
var script = document.createElement('script');
script.src = "path to your src";
// load event
script.onload = function () {
//some staff
};
document.head.appendChild(script);
Also, for you, I'll recommend reading this gist.
Another good information.

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.

How can I load js files in specific pages using jQueryMobile?

It's a known fact that jQueryMobile loads pages with ajax and is not including in DOM the header content in every pages.
I need to load a custom js file in some pages, how can I achieve this? Until now I have placed the .js files in the body, but there are some problems with the code there too so it's not a good workaround. Until I can find a solution I will use the rel="external" workaround, but I really need to find an answer to my question.
You could try including the custom script within the data-role="page" div in pages where you want to use those javascript.
From JQM docs:
Another approach for page-specific scripting would be to include
scripts at the end of the body element. If you include your custom
scripting this way, be aware that these scripts will execute when that
page is loaded via Ajax or regular HTTP, so if these scripts are the
same on every page, you'll likely run into problems. If you're
including scripts this way, we'd recommend enclosing your page content
in a data-role="page" element, and placing scripts that are referenced
on every page outside of that element. Scripts that are unique to that
page can be placed in that element, to ensure that they execute when
the page is fetched via Ajax.
You could use some javascript to dynamically add the js file to the DOM.
This is demoed here: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

jQuery append doesn't work fully with <script> tag

Appending a script element using jquery rather than putting it in the html by hand seems to lead to very different results. For instance
snaphtml = '<script src="http:\/\/seadragon.com\/embed\/lxe.js?width=auto&height=400px"><\/script>';
$('#content').append(snaphtml);
destroys the layout of my page, but putting the script element in the page directly works fine.
I have posted a test case online:
Working example with script in html.
Broken example with script appended via jquery.
The second div should not be deleted / invisible once the silverlight object is added.
Ideas?
I would recommend you to use $.getScript method for loading external script files programmatically:
$.getScript('path/to/script.js', function() {
alert('Script loaded.');
});
The script load is made asynchronously, and as you see in the above example, you can specify a callback function that will be executed when your external file has been loaded and is ready to use.
Tristan, you will not be able to include the script you reference dynamically onto the page after it has finished loading. The external script is using document.write which will only work correctly when called before the page has finished loading. This is why your static implementation works fine, and your dynamic one tears the page apart.
You might want to put together a dummy HTML file that just has a basic HTML structure and this script in it already. Then dynamically add an iframe to your page that loads the HTML. There are even more dynamic ways to make it work with an iframe, but that would be the easiest.
Try to use $.getScript:
$.getScript("http://seadragon.com/embed/lxe.js?width=auto&height=400px");
Edit:
The provided script is using document.write, which is likely causing your problems: you cannot add it dynamically at the middle of the page. Try loading SeaDragon as shown here:
http://www.seadragon.com/developer/ajax/getting-started/
try to break script tag like
snaphtml = '</sc'+'ript>'

Categories

Resources