Loading Content Into div - Resource Issue - javascript

I have a web component which another group wants to include in their web application.
They have asked that I render my page into theirs by rendering into a div. From my understanding they are going to provide an html page similar to this.
TheirComponenetPopupWindow.html
<html>
...
<script src="myscript.js"></script>
...
<div id='render_here'></div>
</html>
where myscript.js will be a script I will need to write.
Now, I have seen countless examples on stackoverflow where I can use $(#render_here).load(..) or $.ajax(..,{..}). However, all of these leave me with a serious problem. That all resources my page loads are now relative to the page I am being rendered into. This off course breaks my page as all of my scripts, images, and css files fail to load.
Is anyone aware of how I can use the methods mentioned above, or maybe a method I am unaware of, where I can render into a div and not break my resources?

You can try to create a iframe in the render_here div, and set the src of iframe with you page url.

You will need rewrite your code using absolute URLs if you want them to be portable to other locations such as a third party's site.
If you don't require interaction between your code and content on the third party page then an iframe would probably save you a lot of time and effort, but access to the third party's page would be prevented from within the iframe.

Related

Load external page inside div and change it

I am trying to figure out how to load an external page inside a div and change it's HTML / CSS. Is it possible?
I got stuck with Same-origin policy, since it doesn't let edit html with a different origin.
For clarify, I want to highlight some content inside it's page and share it.
What are the restrictions to do that and possible ways to solve?
While this might be a really bad idea from a security standpoint, you could do an Ajax GET on the page you want to include and inject its content in the div using the html() jQuery function (strip the .. tags beforehand).
You will be able to tinker with the HTML, but you won't get the stylesheets this way.
Loading external pages inside your page seems like a bad idea to me, though, as it might expose you to XSS and other exploits if the remote page scripts are executed.
Another solution would be to use an iframe, however old-fashioned it may sound.

Why I have to put all the script to index.html in jquery mobile

I have used $.mobile.changepage to do the redirect in my phonegap+jquerymobile projects. However what makes me confused is that I need to put the script of all the pages to the same file index.html. If not, the redirect page can not execute the function in its header.
for example, my index.html seem to be
$(document).bind("deviceready",function(){$.mobile.changepage("test.html");})
then, my device will redirect to test.html which seem to be
$("#btnTest").click(function(){alert("123");})
<button id="btnTest">Test</button>
However, the script will never execute in test.html. Then I put the script to index.html, what I expect to be is done. Whatever, if I put all the script to the same page, the project will become harder and harder to be preserved. Appreciated for your help.
Intro
This article can also be found HERE as a part of my blog.
How jQuery Mobile handles page changes
To understand this situation you need to understand how jQuery Mobile works. It uses ajax to load other pages.
First page is loaded normally. Its HEAD and BODY is loaded into the DOM, and they are there to await other content. When second page is loaded, only its BODY content is loaded into the DOM. To be more precise, even BODY is not fully loaded. Only first div with an attribute data-role="page" will be loaded, everything else is going to be discarded. Even if you have more pages inside a BODY only first one is going to be loaded. This rule only applies to subsequent pages, if you have more pages in an initial HTML all of them will be loaded.
That's why your button is show successfully but click event is not working. Same click event whose parent HEAD was disregarded during the page transition.
Here's an official documentation: http://jquerymobile.com/demos/1.2.0/docs/pages/page-links.html
Unfortunately you are not going to find this described in their documentation. Ether they think this is a common knowledge or they forgot to describe this like my other topics. (jQuery Mobile documentation is big but lacking many things).
Solution 1
In your second page, and every other page, move your SCRIPT tag into the BODY content, like this:
<body>
<div data-role="page">
// And rest of your HTML content
<script>
// Your javascript will go here
</script>
</div>
</body>
This is a quick solution but still an ugly one.
Working example can be found in my other answer here: Pageshow not triggered after changepage
Another working example: Page loaded differently with jQuery-mobile transition
Solution 2
Move all of your javascript into the original first HTML. Collect everything and put it inside a single js file, into a HEAD. Initialize it after jQuery Mobile has been loaded.
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="index.js"></script> // Put your code into a new file
</head>
In the end I will describe why this is a part of a good solution.
Solution 3
Use rel="external" in your buttons and every elements you are using to change page. Because of it ajax is not going to be used for page loading and your jQuery Mobile app will behave like a normal web application. Unfortunately this is not a good solution in your case. Phonegap should never work as a normal web app.
Next
Official documentation, look for a chapter: Linking without Ajax
Realistic solution
Realistic solution would use Solution 2. But unlike solution 2, I would use that same index.js file and initialize it inside a HEAD of every possible other page.
Now you can ask me WHY?
Phonegap like jQuery Mobile is buggy, and sooner or later there's going to be an error and your app will fail (including loaded DOM) if your every js content is inside a single HTML file. DOM could be erased and Phonegap will refresh your current page. If that page don't have javascript that it will not work until it is restarted.
Final words
This problem can be easily fixed with a good page architecture. If anyone is interested I have wrote an ARTICLE about good jQuery Mobile page architecture. In a nut shell I am discussing that knowledge of how jQuery Mobile works is the most important thing you need to know before you can successfully create you first app.
Unlike normal ordinary HTML pages, jQuery Mobile uses ajax technology when navigating between pages. So make sure to import all your JS files and libraries in all your html pages.
If you notice closely you will see that JS files from previous page is taken into consideration when loading the second page. But if you force rrefresh the current page then the js files of the current page will be effective.
So as I said earlier make sure to import the js files in all the html files.
Also no need to call deviceready, use following syntax to call your page specific js functions
$(document).on('pageshow', '#YourPageID', function(){
// Your code goes here
});
Jquery Mobile uses ajax to load a "page". A "page" here is a div with data-role=page. If you load a physical page index.html, you can navigate using changePage to any "page" div inside that page.
However, if you want to load a "page" from other physical page, jQM will only load the first "page" div from that page. What actually happen is you do not change page, jQM just load that particular "page" div using ajax and inject it to your current page.
You have two possible architecture where you put all your "pages" in a html page and navigate from there. Or you can have multiple page architecture. You can always mix this.
To physically change page, you need to add rel=external to your link.

Should use Head.js or just minified scripts before </body> with scripts in the markup?

I have the optimisation problem — my site uses 2 (pretty large) javascript resources:
application.js (minimised jquery, jquery-ui, underscore-js and some shared scripts, 120KB total)
controller-specific file (some modules required for the page + interactions, 4KB total)
I have some scripts in the views that format/convert markup with JavaScript (dependable on both jQuery and my controller-specific JS code) so I need to wait either for $(document).ready or head.ready and it makes the part of website invisible to prevent the flash of unstyled content :(
Now my question comes: should I use head.js for it or just stick with the "before " scripts? Are there any smart ways to speed up page loading time in this case?
Update:
Here's the part of the code (see versusio.com for full code, landing page):
<html>
<head>
... usual stuff
<link (css stuff) />
<script src="head.js"></script>
<script>
// Here some global variables are set like cache keys, actual locale code etc., not dependable on jQuery or any other JS code from the JS assets
</script>
</head>
<body>
... page content
<div id="search">!-- here some code with the "display: none" style to prevent flash of unstyled content</div>
<script>
// Here is code that positions and processes some styles and adds some interactions to the #search div
Application.Position.In.Center($(#search), $(document));
</script>
... more page content
... another "display: none" div and accompanying script
... rest of the page content
<script type="text/javascript">head.js( { 'application': 'application.js' }, { 'landing': 'landing.js' } );</script>
</body>
</html>
First ask yourself this question: Do i really need all this javascript loaded when a user visits my page?
When first loading your website, you actually only need the autocomplete-functionality, the rest isn't needed on load. So you could go for a seperated approach. My advice would be the following:
Build this page without any javascript-functionality and then enhance it with javascript, get rid of the inline styles and scripts.
After you have done this, load the scripts you actually need, you can do this in the head or just before the end of the body
Use a CDN for Jquery, jquery-ui, underscore and the other libraries. If a user already loaded these libraries from another website, you have a performance bonus.
Last of all, already asynchronously load the javascript needed later on, so the user already has the scripts when he hits the compare-button.
Small tweaks:
Use a tool like ySlow or the networking graph in your favorite browser to look for any bottlenecks. It looks like gzipping is not enabled, try and do that.
Do you really need to load the facebook/google/twitter/third-party stuff in the head or could that be done when the page is loaded?
Is the server as fast as possible? It looks like it takes almost halve a second to get the HTML.
I hope i helped you out for a bit, good luck with the performance tweaking!
You could put mask layer that cover all pages with fixed style, then hide or destroy it when loading process finished. That way there's no need to hidden each content, instead it will be covered with mask div
I think, put a load scripts on the bottom of the page (as the last tags in the body). That javascript it will not block the drawing page, like now.
Saw the view source of your page.
There are some inline scripts which can block rendering. Such as this
Application.i18n = {"comparisons":{"off_ratio":
More here. http://calendar.perfplanet.com/2012/deciphering-the-critical-rendering-path/
Quick way: Moving them to the end of body tag.
Best way: They should be loaded as external scripts - with very good cache headers.
May be, you are doing that as - you have to load those messages based on user locale - You can create separate JS files for every locale during your build process - an they can be linked / loaded as external JS files with good cache headers
Another reason, why you might need inline scripts - to take note of the initial loading time. which is not necessary - as the modern browsers provide us with perfomance timings.
http://www.html5rocks.com/en/tutorials/webperformance/basics/
Moving it as an external script file - will also be good for your site security - in case, if you will be trying CSP.
http://updates.html5rocks.com/2012/11/Content-Security-Policy-1-0-is-officially-awesome.
Defer / async attributes.
ga.js is set with async attibute - but other JS files can be tried with defer attributes. Also, as a general rule of thumb, delay loading resources as far as possible,load only when it is needed.
window.onload - $.ready
Starting your script execution with $.ready is always going to be better than window.onload.
because, window.onload fires only after all the images, inner iframes gets loaded.
The following links might be useful.
https://developers.google.com/speed/
The Progressive JPEGs post in http://calendar.perfplanet.com/2012/
http://blog.chriszacharias.com/page-weight-matters
http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-performance/
A lot of further optimisations are possible. All the best.

Js, is it really better to include at the end of the page?

Currently I'm doing this.
<js>
</head>
Pagespeed and other articles suggest doing this instead.
<js>
</body>
</html>
I would love the opinion of stack overflow!
Thank you
The only issue with putting all your scripts at the end of the body is that sometimes page components drop little bits of Javascript on the page that may assume the existence of some Javascript facility. Other than that, there's nothing wrong with it and it can help make your pages appear to load/render faster.
You might also look into tools like LabJS (http://labjs.com) as a more sophisticated way to load your Javascript.
Use progressive enhancement so that your page will work whether JavaScript is enabled or not. Then, move the Javascript to the bottom of the page so that your page's content loads and renders first. And, as always, test the performance of your page using Page Speed or YSlow.
The default way of including Javascript is to do it from the head tag, that's where they normally belong. That's where you should start out, and only move the scripts if you need to optimise the loading of the page.
There are some reasons to put some scripts later in the page:
To make the content of the page load earlier
To make the page less sensetive to slow loading external scripts
There are some special considerations if you move scripts down the page:
Some scripts doesn't work if the load after the content.
You should make sure that the content doesn't look bad or does anything nasty if the user tries to use it before the scripts are loaded.

Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?

I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.
But where exactly and when?
Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section?
There are two possibilities for truly unobtrusive scripts:
including an external script file via a script tag in the head section
including an external script file via a script tag at the bottom of the body (before </body></html>)
The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.
If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.
And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers.
It's never so cut and dry - Yahoo recommends putting the scripts just before the closing </body> tag, which will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document).
However, if you have some code you want to run on page load, it will only start executing after the entire page has loaded. If you put the scripts in the <head> tag, they would start executing before - so on a primed cache the page would actually appear to load faster.
Also, the privilege of putting scripts at the bottom of the page is not always available. If you need to include inline scripts in your views that depend on a library or some other JavaScript code being loaded before, you must load those dependencies in the <head> tag.
All in all Yahoo's recommendations are interesting but not always applicable and should be considered on a case-by-case basis.
As others have said, place it before the closing body html tags.
The other day we had numerous calls from clients complaining their sites were extremely slow. We visited them locally and found they took 20-30 seconds to load a single page. Thinking it was the servers performing badly, we logged on - but both web and sql servers were ~0% activity.
After a few minutes, we realised an external site was down, which we were linking to for Javascript tracking tags. This meant browsers were hitting the script tag in the head section of the site and waiting to download the script file.
So, for 3rd party/external scripts at least, I'd recommend putting them as the last thing on the page. Then if they were unavailable, the browser would at least load the page up until that point - and the user would be oblivious to it.
To summarize, based on the suggestions above:
For external scripts (Google analytics, 3rd party marketing trackers, etc.) place them before the </body> tag.
For scripts that affect page layout, place in head.
For scripts that rely on 'dom ready' (like jquery), consider placing before </body> unless you have an edge-case reason to place scripts in head.
If there are inline scripts with dependencies, place the required scripts in head.
If you want to tinker with the position of your scripts, YSlow is a great tool for giving you a flavour if it's going to improve or hurt performance. Putting javascript in certain document positions can really kill page load times.
http://developer.yahoo.com/yslow/
No it should not be after the </html> as that would be invalid. The best place to put scripts is right before the </body>
This is basically because most browsers stop rendering the page while they eval the script that you provide. So its OK to put non-blocking code anywhere in the page (I'm mainly thinking of things that attach functions to the onLoad event, since event binding is so fast as to effectively be free). A big killer here is at the beginning of the page putting in some ad server script, which can prevent any of the page loading before the ads have totally downloaded, making your page load times balloon
If you put it at the bottom, it loads last, hence speeding up the speed that the user can see the page. It does need to be before the final </html> though otherwise it won't be part of the DOM.
If the code is needed instantly though, then put it in the head.
It's best to put things like blog widgets at the bottom so that if they don't load, it doesn't affect the usability of the page.

Categories