User Google Closure to lazy load javascript - javascript

I'm especially liking the ability to require other javascript classes by using Google Closure, but I'm wondering if it's possible to use goog.require to lazy load other javascript classes. When I trying using goog.require after the page has loaded, it seems to refresh or go blank :(
Any way to get a script on demand, and maybe set it up with a callback, so I can run some javascript when it's done loading?

Closure Library ModuleManager:
https://github.com/google/closure-library/blob/master/closure/goog/module/modulemanager.js

goog.require is not designed to be used to load any script. However, there is nothing special in lazy-loading script files on demand. Simply create node dynamically and add it to your page:
function require(src)
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.body.appendChild(script);
}
The above function will load the script from the URL specified by the src parameter.
The callback is another story. You do not get an event fired after a script is loaded. If you want to get notified when the script has loaded, you need to notify of the loaded script from the script itself. For example, you can call a predefined function on your page as a last statement in the javascript file you are loading. Once this function is called, you know the script has finished loading. To do that, however, you need to be able to modify the loaded script file.
A similar approach for notifying a script has loaded is used with JSONP. The JSONP data is retrieved using the same approach above - you add a dynamically created script node to the page. However, by default, returning data from the server does not cause a change of state. A function call is needed to indicate something has happened (e.g. the data has arrived). With JSONP, you specify the name of a function in the URL of the JSONP request. The server then returns a piece of javascript where the function you specified is called, passing the JSON data in an argument.
All this is to suggest you need to be able to call a function on page after the script has loaded.

Related

Javascript stop Loading scripts and may load scripts again if user consents

I am trying to implement GDPR solution. Need to stop the certain scripts either functions or src scripts.
I am able to identify the scripts using "var scripts = document.getElementsByTagName("script");" and iterate thru them after page is loaded.
How do i stop them from being executed. Need eventlistener etc..
If you have any working code it would be helpful. I found somethere that the script type is changed to text/plain etc.. so the script will not be executed and after getting consent, the type is changed back to script/javascript and loaded onto the page dynamically.
How do I do this?
Your help is appreciated.
Venkat
hey i don't understand what you trying to achieve but i have an idea
if you wanna fire a certain script after doing for example action A
have empty <script></script>
const script = document.getElementsByTagName("script");
if (action A == true){
// the path to the script file
script.src ='js/script.js'
}

How to call a function only when all scripts are loaded?

I am sharing a script tag with client to deploy my web application on client's website.
Basically by this way, he can embed my app wherever he want on his site.
The script which I give him just calls one action method in my MVC application and receives a javaScript as a response.
As a fist step, this returned JavaScript inserts all js and css references (required by my application) in the client's head tag
function createScriptElement(src) {
var tmp = document.createElement("script");
tmp.src = src;
var head = document.getElementsByTagName("head")[0];
head.appendChild(tmp);
};
and then in second step, it writes the html content inside one dynamic div.
document.write(format("<div id='mycontainer'>{0}</div>{1}", AppHtml,initcalls ));
The "initcalls" contains the initial function in my app's javascript which I expect to execute immediately. So I put it in Script tag as below.
contents of initcalls are:
<script type=\"text/javascript\"> function icInitApp() { ..... }; </script>
The problem is: there are some dependencies in my application on the js references. The HTML is getting loaded before the head tag in client's page recognizes and loads the js references.
Is there any way to hold my (thus dynamically rendered) application's init function until all js references are fully loaded by head tag?
I tried giving setTimeout() with 5 seconds but it will not be proper solution accepted by client.
A similar kind of situation is discussed in the link below
How to detect if javascript files are loaded?
You can also try to use the $(window).load() event since this will be fired when the page is fully loaded.
$(window).load(function(){
//your code here
});
PS: Be aware that you will need to load the jQuery in your page to make the above code work.
You can try with jQuery:
$(document).ready(function()){
// Your code goes here
};

jQuery load function modified to include relevant scripts

Ive been playing with the load, get, ajax and get scripts function.
The most appropriate to the majority of function where I intend to load in content on a page would be the load function. It is a simple and effective way of getting the relevant content from an associate page.
But since it does not include scripts and the new content does not respond to the pages ready. functions I was wondering if there was a simple enhancement we could make that would allow the scripts of the page to be refreshed to include loaded content.
Something like
function loadall(url,container){
$(container).load(url);
scritps.reset();
}
What would be the way of doing this.

How to load a script file and execute it?

I have feedburner script which displays feeds, it looks like this:
<script src="http://feeds.feedburner.com/cnn/HIkg?format=sigpro" type="text/javascript" ></script>
I want to load this script which is on a different html page, so basically I'm loading html file with this script in it using:
$('#' + items[i]).load('content/' + items[i] + '.html');
This piece of code does load the html page but the script is not executed(working). How do I get the script to work once loaded?
According to the documentation :
Script Execution
When calling .load() using a URL without a suffixed
selector expression, the content is passed to .html() prior to scripts
being removed. This executes the script blocks before they are
discarded. If .load() is called with a selector expression appended to
the URL, however, the scripts are stripped out prior to the DOM being
updated, and thus are not executed.
If your url is just a plain url without a selector specified than the script should execute before it is removed.
Check the value of items[i] and check if it is a plain url without a selector or not.
If the url looks fine, you might be running into a cross-side scripting issue. The documentation also mentions:
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
If possible though I still would recommend for any script to be in an external file as that is good practice and doesn't clutter the html. Then you can use .getScript() as recommended by Raminson.
You can use the $.getScript() utility function:
Load a JavaScript file from the server using a GET HTTP request, then execute it.
$.getScript("/test.js")

Modifying Javascript to run after AJAX load

I am using a little javascript thingy (app?) from http://code.google.com/p/tumblrbadge/ to load my most recent tumblog post into my webpage. However, when I load the 'tumblr' section with AJAX using Jquery, the script does not get executed. I understand why this is and that I need to include the javascript file in the and execute it after the AJAX load is complete. My problem is this: I do not fully understand the tumblrbadge code and, when I include the script in the and call tumblrBadge() after loading, it does not run. How must I modify the tumblrbadge code to allow it to be run on demand from the ?
All of this is hosted at http://jquerytest.webs.com
It looks like your problem is that the script tags within the tumblr section of your site are not being executed. When you insert html into a page using ajax, you have to parse out the contents of any script tags and execute them separately.
After the content of the tumblr tab is inserted in your page, get all of its script tags with $("#contentOfTumblrTab script") and evaluate their innerHTML using eval().
Try $(window).onload instead of $(document).ready.

Categories