I want to lazy load all the 3rd party JS/CSS after my home page is displayed since the external plugins etc are used when user navigates away from home page onto some specific module.
So far I have succeeded for normal .js & .css external libraries thanx to http://wonko.com/post/lazyload-200-released
However this fails for a path like this http://maps.google.com/maps/api/js?sensor=true
Code:
LazyLoad.js('http://maps.google.com/maps/api/js?sensor=true', function () {
alert('Your JS has been loaded');
});
I think the solution would be how to lazy-load web url?
I believe you want something like:
$.getScript('http://maps.google.com/maps/api/js?sensor=true');
using jQuery. The API will give details of the call back. Else Google may have some mechanism requiring it to be present from load. Just a guess.
Found a solution:
Check the URL:'http://maps.google.com/maps/api/js?sensor=true'
You would find main.js is being imported by it . A simple getScript for sensor=true will not give whole google object so next import also required.
var t=setTimeout(function(){
jQuery.getScript('http://maps.google.com/maps/api/js?sensor=true');
jQuery.getScript('http://maps.gstatic.com/intl/en_us/mapfiles/api-3/10/20/main.js');
},1000);
Related
So I'm trying to inlcude an external .js file in my SAPUI5 Controller.
jQuery.sap.includeScript("externalLibrary.min.js",
function() {
//initalizing objects from library
});
However, the callback which should be called once the script is loaded, never gets called. The error message it gives me is:
"externalLibrary.min.js:16 Uncaught TypeError: Cannot read property
'Constructor' of undefined"
Whats another way I could do this? I was looking into jQuery.sap.registerModulePath() and jQuery.sap.registerResourcePath() but couldn't find a good example of the use of these nor an explaination of the difference between the two online.
Thanks a lot!
You can try jQuery.sap.includeScript(vUrl, sId?, fnLoadCallback?, fnErrorCallback?)
https://sapui5.hana.ondemand.com/docs/api/symbols/jQuery.sap.html#.includeScript
in fiori launchpad based app , we use component.js as root , so we don't have index.html to include scripts (if you use XML view instand of HTML view).
try
jQuery.sap.includeScript({
url: "https://maps.googleapis.com...",
id: "IncludeGoogleMapsScript"
}).then(function() { ... })
Not working in portal service , fallback is provided :
UsingjQuery.sap.includeScript().then() in HCP Firori Launchpad
You can use jQuery.sap.registerResourcePath('lib', URL) and then jquery.SAP.require('lib.file'). You can do both one after another or register in the init and later require. Does not matter. I don't have an example at hand as I am on a phone but it works. What you need to keep in mind is that this example would load something like URL/file.js so you need to adjust accordingly. The name you give to the lib does not matter.
You can also inject a script tag into the current page ,however, the require will load the external lib synchronously while if you inject a script tag you need to wait until it is loaded with a callback.
PS: the capitalization on those methods is not right
Got it! For future reference, it works to load the files from the index html like so:
<script src="library.js"></script>
The main problem was that I was trying to include external dependencies which also contained jQuery. So, I had to remove that from the file and now it's working.
I have the following function that activates when I click on some links:
function showPage(page) {
var History = window.History;
History.pushState(null,null,page);
$("#post-content").load(page + ".php");
}
The content of the page updates, the URL changes. However I know I'm surely doing something wrong. For example when I refresh the page, it gives me the Page Not Found error, plus the link of the new page can't be shared, just because of the same reason.
Is there any way to resolve this?
It sounds like you're not routing your dynamic URLs to your main app. Unless page refers to a physical file on your server, you need to be doing some URL rewriting server-side if you want those URLs to work for anything other than simply being placeholders in your browser history. If you don't want to mess with the server side, you'll need to use another strategy, like hacking the URL with hashes. That way the server is still always serving your main app page, and then the app page reads the URL add-on stuff to decide what needs to be rendered dynamically.
You need to stop depending on JavaScript to build the pages.
The server has to be able to construct them itself.
You can then progressively enhance with JavaScript (pushState + Ajax) to transform the previous page into the destination page without reloading all the shared content.
Your problem is that you've done the "enhance" bit before building the foundations.
There is javascript on my webpage, but I need to hide it from my users (I don't want them to be able to see it because it contains some answers to the game.)
So I tried using Jquery .load in order to hide the content (I load the content from an external js file with that call). But it failed to load. So I tried ajax and it failed too.
Maybe the problem comes from the fact that I'm trying to load a file located in my root directory, while the original page is located in "root/public_html/main/pages":
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url : "../../../secret_code.js",
dataType: "text",
success : function (data) {
$("#ajaxcontent").html(data);
}
});
});
</script>
1) Why can't I load a file from the root directory with ajax or load method?
2) Is there another way around?
PS: I'm putting the file in the root directory so people can't access it directly from their browsers...
1) if the file isn't accessible via web browsers, than it's not accessible via ajax (ajax is part of the web browsers
2) try /secret_code instead of ../../../secret_code.js
What is your system setup? Are you using a CMS?
Even if you add the javascript to the page after page load a user with a tool like firebug can go and view it. I don't think what you are doing is really going to secure it. An alternate solution is that you could minify and obfuscate the javascript that you use in your production environment. This will produce near unreadable but functioning javascript code. There are a number of tools that you can run your code through to minify and obfuscate it. Here is one tool you could use: http://www.refresh-sf.com/yui/
If that isn't enough then maybe you could put the answers to the game on your serverside and pull them via ajax. I don't know your setup so I don't know if that is viable for you.
Navigate to the URL, not the directory. Like
$.ajax({
url : "http://domain.com/js/secret_code.js",
..
Even if you load your content dynamicly, it's quite easy to see content of the file using firebug, fiddler or any kind of proxy. I suggest you to use obfuscator. It will be harder for user to find answer
Take a look at the jQuery.getScript() function, it's designed for loading Javascript files over AJAX and should do what you need.
Try jQuery's $.getScript() method for loading external
Script files, however, you can easily see the contents of the script file using Firebug or the developer toolbar!
Security first
You can't access your root directory with JavaScript because people would read out your database passwords, ftp password aso. if that would be possible.
You can only load files that are accessible directly from browsers, for example, http://www.mydomain.com/secret_code.js
If it can't be accessed directly by the browser, it can't be accessed by the browser via ajax. You can however use .htaccess to prevent users from opening up a js file directly, though that doesn't keep them from looking at it in the google chrome or firebug consoles.
If you want to keep it secret, don't let it get to the browser.
I read (somewhere else on this site) you can't reload (or inject javascript) onto a page that is already rendered.
Is there any other way of doing this. For instance an iFrame?
I have a recent comment widget.js and I need to constantly get it to reload without reloading the whole page.
Any ideas?
edit: The site has recent comments on it and they are displayed via a recentcomment.js
Once the page is loaded it doesn't update itself unless you reload the page. I want it to update itself, a way to do this is to just reload the js file on the page, correct?
Why do you need to do this? It seems to me that there's probably a more appropriate solution to your problem.
But to answer it:
var elm = document.createElement("script");
elm.src = "Widget.js";
document.getElementsByTagName("head")[0].appendChild(elm);
Hope I didn't write any mistakes...
Rather than reloading the file, you can have all the implementation of the file contained in a function and then call the function every minute using the setTimeout() function.
Alternatively, if you want to reload it because the content of the file might have changed, it would probably be better to move that part of the code out to some external file and then use a function (running every minute with setTimeout()) to load the new content you need.
You can make cross-domain AJAX requests using certain methods, so you could make an AJAX request for the script file and parse it yourself. Parsing it yourself probably isn't an optimal solution, but it looks like you're dealing with a brain-dead service provider anyways.
Look at this guy's jQuery mod for an example:
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
Once you get the data from the 3rd party, you could probably use some combination of regex and JSON parser to extract the comments.
With a single page app, where I change the hash and load and change only the content of the page, I'm trying to decide on how to manage the JavaScript that each "page" might need.
I've already got a History module monitoring the location hash which could look like domain.com/#/company/about, and a Page class that will use XHR to get the content and insert it into the content area.
function onHashChange(hash) {
var skipCache = false;
if(hash in noCacheList) {
skipCache = true;
}
new Page(hash, skipCache).insert();
}
// Page.js
var _pageCache = {};
function Page(url, skipCache) {
if(!skipCache && (url in _pageCache)) {
return _pageCache[url];
}
this.url = url;
this.load();
}
The cache should let pages that have already been loaded skip the XHR. I also am storing the content into a documentFragment, and then pulling the current content out of the document when I insert the new Page, so I the browser will only have to build the DOM for the fragment once.
Skipping the cache could be desired if the page has time sensitive data.
Here's what I need help deciding on: It's very likely that any of the pages that get loaded will have some of their own JavaScript to control the page. Like if the page will use Tabs, needs a slide show, has some sort of animation, has an ajax form, or what-have-you.
What exactly is the best way to go around loading that JavaScript into the page? Include the script tags in the documentFragment I get back from the XHR? What if I need to skip the cache, and re-download the fragment. I feel the exact same JavaScript being called a second time might cause conflicts, like redeclaring the same variables.
Would the better way be to attach the scripts to the head when grabbing the new Page? That would require the original page know all the assets that every other page might need.
And besides knowing the best way to include everything, won't I need to worry about memory management, and possible leaks of loading so many different JavaScript bits into a single page instance?
If I understand the case correctly, you are trying to take a site that currently has pages already made for normal navigation, and you want to pull them down via ajax, to save yourself the page-reload?
Then, when this happens, you need to not reload the script tags for those pages, unless they're not loaded onto the page already?
If that is the case, you could try to grab all the tags from the page before inserting the new html into the dom:
//first set up a cache of urls you already have loaded.
var loadedScripts = [];
//after user has triggered the ajax call, and you've received the text-response
function clearLoadedScripts(response){
var womb = document.createElement('div');
womb.innerHTML = response;
var scripts = womb.getElementsByTagName('script');
var script, i = scripts.length;
while (i--) {
script = scripts[i];
if (loadedScripts.indexOf(script.src) !== -1) {
script.parentNode.removeChild(script);
}
else {
loadedScripts.push(script.src);
}
}
//then do whatever you want with the contents.. something like:
document.body.innerHTML = womb.getElementsByTagName('body')[0].innerHTML);
}
Oh boy are you in luck. I just did all of this research for my own project.
1: The hash event / manager you should be using is Ben Alman's BBQ:
http://benalman.com/projects/jquery-bbq-plugin/
2: To make search engines love you, you need to follow this very clear set of rules:
http://code.google.com/web/ajaxcrawling/docs/specification.html
I found this late and the game and had to scrap a lot of my code. It sounds like you're going to have to scrap some too, but you'll get a lot more out of it as a consequence.
Good luck!
I have never built such a site so I don't know if that is nbest practice, but I would put some sort of control information (like a comment or a HTTP header) in the response, and let the loader script handle redundancy/dependency cheching and adding the script tags to the header.
Do you have control over those pages being loaded? If not, I would recommend inserting the loaded page in an IFrame.
Taking the page scripts out of their context and inserting them in the head or adding them to another HTML element may cause problems unless you know exactly how the page is build.
If you have full control of the pages being loaded, I would recommend that you convert all your HTML to JS. It may sound strange but actually, a HTML->JS converter is not that far away. You could start of with Pure JavaScript HTML Parser and then let the parser output JS code, that builds the DOM using JQuery for example.
I was actually about to go down that road for a while ago on a webapp that I started working on, but now I handed it over to a contractor who converted all my pure JS pages into HTML+JQuery, whatever makes his daily work productive, I dont care, but I was really into that pure JS webapp approach and will definitely try it.
To me it sounds like you are creating a single-page app from the start (i.e. not re-factoring an existing site).
Several options I can think of:
Let the server control which script tags are included. pass a list of already-loaded script tags with the XHR request and have the server sort out which additional scripts need to be loaded.
Load all scripts before-hand (perhaps add them to the DOM after the page has loaded to save time) and then forget about it. For scripts that need to initialize UI, just have each requested page call include a script tag that calls a global init function with the page name.
Have each requested page call a JS function that deals with loading/caching scripts. This function would be accessible from the global scope and would look like this: require_scripts('page_1_init', 'form_code', 'login_code') Then just have the function keep a list of loaded scripts and only append DOM script tags for scripts that haven't been loaded yet.
You could use a script loader like YUI Loader, LAB.js or other like jaf
Jaf provides you with mechanism to load views (HTML snippets) and their respective js, css files to create single page apps. Check out the sample todo list app. Although its not complete, there's still a lot of useful libraries you can use.
Personally, I would transmit JSON instead of raw HTML:
{
"title": "About",
"requires": ["navigation", "maps"],
"content": "<div id=…"
}
This lets you send metadata, like an array of required scripts, along with the content. You'd then use a script loader, like one of the ones mentioned above, or your own, to check which ones are already loaded and pull down the ones that aren't (inserting them into the <head>) before rendering the page.
Instead of including scripts inline for page-specific logic, I'd use pre-determined classes, ids, and attributes on elements that need special handling. You can fire an "onrender" event or let each piece of logic register an on-render callback that your page loader will call after a page is rendered or loaded for the first time.