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
};
Related
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'
}
I'm truing to execute a yui js script with js.executeScript Selenium's method.
The script is being executed by selenium webdriver in order simulate a "click" on hybrid mobile app (the button is webview)
String IncludeYUI = "script = document.createElement('script');script.type = 'text/javascript';script.async = true;script.onload = function(){};script.src = '"
+ YUI_PATH
+ "';document.getElementsByTagName('head')[0].appendChild(script);";
js.executeScript(IncludeYUI);
where the YUI_PATH is an url - https://cdnjs.cloudflare.com/ajax/libs/yui/3.18.0/yui/.....
The problem is that I do not have an access to the global network from the current site.
so I was thinking to save the script under the project and just to load it from FS.
But this is a js , no access to the FS ...
Any ideas how to load the script ?
Thanks
So, you're loading an html page somewhere, right? Conceptually you would load your JS file the same way: you make a request to your server to load the JS file, just like you did to load your html page.
That would look like this:
<script src="scripts/yourFile.js">
Also, I've never seen anyone loading a js file like you're doing in your code sample...I would most definitely just recommend putting a script tag in your html.
You may want to post your html code as well; we'll be able to provide better help. I'll update this answer accordingly if needed.
Finally , after many tries , some1 has suggested me to work with jquery.
after some digging , I've used executeScript with jquery's tap , and it worked...
$('#btn_login_button').trigger('tap');
I was wondering all other methods with click and element's coordinates didn't work
On my site, there is an area where I load several different widgets via AJAX. Some widgets need an external JS script that the rest of my page doesn't so I'd rather not load that script until the window opens for that specific widget.
the ajax code is:
$.get(content_url, null, function(rawResponse, status, xhr) { // get new data
content_target.html(rawResponse); // replace with new data
loadingSomething = false;
});
The content loaded is:
<script type="text/javascript" src="http://www.bandsintown.com/javascripts/bit_widget.js"></script>
<script type="text/javascript">var widget = new BIT.Widget({"artist": "{{ id }}"});widget.insert_events();</script>
But when I do this, the widget doesn't load. I'm guessing it's because the external script isn't loading.
Any ideas on how to make this work? Keep in mind I'm loading several different widgets with their own external scripts, so it'd be tough to add that into the JS since that's standardized across all widgets.
Thoughts?
It's a bit of a headache to load scripts like this, especially if you're trying to make a cross-domain ajax request. Consider using HeadJS to improve load times without making things hellishly complicated.
JavaScript loader
Load scripts in parallel but execute in order
head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() {
// all done
});
Head JS loads JavaScript files like images without blocking the page. Your page will be faster even with a single combined file.
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.
In javascript, as a script loaded from somer host, is there any way to know what server/host I was loaded from? I need to make additional ajax requests back to that host and would prefer to figure out the host dynamically.
So if you include a javascript file on a page
<script src="http://somehost.com/js/test.js"></script>
when that javascript execute, within test.js ...
var host_loaded_from = ??? // should be somehost.com
Thanks
is there any way to know what server/host I was loaded from?
Yes, it's possible except when the script is loaded asynchronously using defer or async attributes since the last script in the DOM may not necessarily be the currently executing script in that case. See the comments by #kangax for more information.
Also, this same question was posted recently.
Inside your test.js, get the last script element which will be the currently being parsed script (test.js in your case), and get its src.
// test.js
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;
One the src is found, parsed the host using regex.
src.match(new RegExp('https?://[^/]*'))
["http://somehost.com"] // for your example
Does the script know its own file name? ("test.js" in the OP question.)
If so, your script could query the dom for all script tags, looking for the ones with a src attribute. But you'd need to watch out for two scripts with the same file name loaded from different servers. Eg
<script src="http://somehost.com/js/test.js"></script>
<script src="http://somehost_number2.com/js/test.js"></script>
Here's JS that looks for all of the script tags in an el:
var scripts = el.getElementsByTagName('SCRIPT');
Nope, sorry.
If the <script> had an id, then maybe. But you can't really rely on that.
Not sure if that can be done with JavaScript. If the script is inside a PHP file do it like this:
...
var host_loaded_from = <?php echo $_SERVER[SERVER_NAME] ?>
...
On my site I include my JS scripts using PHP just for that reason. I'm interested to see if there's a better way.
Due to Same Origin Policy, you can make AJAX requests only to the origin (host + protocol + port), the HTML page (document) was loaded from - which is not necessarily the same as the origin your js was loaded from.
You can use window.location.hostname or document.location.hostname to find out the hostname of the document.