dynamically loading and unloading js files - javascript

Currently I have an website where each page on the site has a corresponding js file that contains a class (well function) defined in it. Currently when the user navigates to another page (which is just ajax content) I remove the old script tag from the page and add a new script tag for the new page. This is working though I was wondering if there could be any problems with this or better ways to do it? I've been thinking of using an AJAX call (XMLHTTPRequest) to get the new js file then using eval to initiate the new page.

What you are doing makes sense because the browser can intelligently cache the js.
Getting the js yourself might prevent the possibility to cache.

Related

Is it possible to alter actual css file using javascript?

I want to modify the CSS file using data that I get from the database. So, after the login, I am getting all the necessary data from DB and update styleSheet using insertRule/deleteRule methods then, redirect to the main page.
Login -> Theme engine page (modify css) -> home page
Theme engine page (theme.html) is an empty HTML page with one JS file (themeEngine.js) which modifies CSS file.
I checked the stylesheet in theme.html it is same as the expected result but, when it redirects to home page the CSS file goes back to its default version. The methods insertRule/deleteRule is not altering an actual file!
I tried importing themeEngine.js to every existing HTML file but in that case, default style appears (for a little amount of time, depending on the internet speed) before the theme engine starts to work and importing js file to every page is quite inconvenient.
I would like to know how can I solve this problem: having a custom style for every user. Is it possible to edit an actual CSS file using JavaScript?
Browsers can't change data on a server without explicit support from it by the server. (Imagine how long the Google homepage would survive otherwise!)
Typically you would need to pick a server-side programming language, use it to write an API, and then interact with it using Ajax.

How can I load a JS async file - OR pass a click event into an anonymous function?

I have a page with many social signin buttons. Rather than loading all the JS files for all those apps, I would rather only load the one file that's needed based on a user click.
So if for example, a users clicks the FB sign in button, it would load the FB.js file, then call the FB.login() function.
I can do this easily asynchronously with jquery. However, most browsers are then blocking the window.open() call because it's not derived directly from the click event.
So my question is, what is a good way to load and execute this script, before continuing? I tried with a synchronous XHR request, but that didn't work because it's cross domain.
Since the popup does actually come downstream from a click event, is there some way to pass that into the anonymous function so it can still allow the popup?
You can do this with vanilla javascript by appending an element to the DOM:
var scriptnode=document.createElement('script')
scriptnode.setAttribute("type","text/javascript")
scriptnode.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(scriptnode)
Replace filename above with the link to your script.
I'm not sure if this will still give you issues with cross-domain limitations, but if you're loading it from the same domain it should be fine. If not, I recommend creating a copy of the script you're trying to load for your site.

Adobe DTM and the timing of referencing an object

I'm running into issues with DTM and the timing of referencing a js object. I noticed that at times, DTM doesn't have access to the js object the web application (ASP.net MVC framework) creates. The js object is created before any of the js from DTM loads but I started having to use "settimeouts" in a few spots to ensure I had context to the object but this is now becoming increasingly more difficult to manage as I'm having to do this in a number of locations.
I was wondering if anyone had any advice on how to delay the loading of the DTM files until I know that I have access to that object? I have a bootstrap file that loads the appropriate DTM files. I was thinking about possibly putting the delay in the bootstrap loader file but I still don't like that solution as I'm also concerned about load time of the pages. Ideas?
-Thanks!
You're right. This can be tricky. Essentially its a race between the DTM page load and execution of your code.
If this is something you need to control on page load, one solution would be to "abort" the original AA request on page load and then, when your object exists, call a direct call rule that will send the data.
I might try something like this:
//Page Load Rule - Adobe Analytics Custom Code Section
s.abort = true // cancel the initial image request on page load
//Check for ASP Object
//Can be done within AA custom code or a custom JS tag
if (MY_OBJ_EXISTS) {
_satellite.track('MY_RULE_TO_SEND_DATA_TO_AA')
}
The same concept can be applied if you have ajax that needs to load before you send data to AA. You can abort the initial call, listen for a callback and send data via a direct call rule.
Hope this helps.

preload javascript (ckeEditor.js wysiwyg) in another page before called

Is there a way to pre-load ckEditor ckEditor before we even open the page in which the ckEditor.js javascript is being called?
I would like to do this as the ckEditor.js is a heavy 350kb file which for some user takes 20-30 sec to upload over the dialup connections. I wanna load it when the user has only opened the front page ( which is just a simple still html) and is busy reading the front page. and by the time he/she moves to the page where ckeditor is used, the ckeditor.js is already loaded and cached.
You can definitely do this by including CKEditor as a js file regularly on your home page, which will cause it to load into the cache before moving on to another page. The problem is that CKEdtior is usally linked to with some arbitrary number as a query string at the end of the file name which makes it uncacheable (ckeditor.js?v=12424324234 or something similar). You'll probably need to get into the CKEditor source (which I remember is a complete nightmare) and do a global find for where that file calls the JS file you're trying to cache, and make sure it doesn't include that variable query string on the end.

Best practices managing JavaScript on a single-page app

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.

Categories

Resources